diff options
Diffstat (limited to 'docs/html/guide/tutorials/views')
29 files changed, 1919 insertions, 0 deletions
diff --git a/docs/html/guide/tutorials/views/hello-autocomplete.jd b/docs/html/guide/tutorials/views/hello-autocomplete.jd new file mode 100644 index 0000000..9f97b32 --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-autocomplete.jd @@ -0,0 +1,114 @@ +page.title=Hello, AutoCompleteTextView +@jd:body + +<p>{@link android.widget.AutoCompleteTextView} is an implementation of the EditText widget that will provide +auto-complete suggestions as the user types. The suggestions are extracted from a collection of strings.</p> + + +<ol> + <li>Start a new project/Activity called HelloAutoComplete.</li> + <li>Open the layout file. + Make it like so: +<pre> +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="horizontal" + android:layout_width="fill_parent" + android:layout_height="wrap_content"> + + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="Country" /> + + <AutoCompleteTextView android:id="@+id/edit" + android:layout_width="fill_parent" + android:layout_height="wrap_content"/> + +</LinearLayout> +</pre> +</li> + +<li>Open HelloAutoComplete.java and insert the following as the <code>onCreate</code> method: +<pre> +@Override +protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit); + ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, + android.R.layout.simple_dropdown_item_1line, R.array.planets); + textView.setAdapter(adapter); +} +</pre> + <p>Here, we create an AutoComplteteTextView from our layout. We then + create an {@link android.widget.ArrayAdapter} that binds a <code>simple_dropdown_item_1line</code> + layout item to each entry in the <code>COUNTRIES</code> array (which we'll add next). + The last part sets the ArrayAdapter to associate with our AutoCompleteTextView.</p> +</li> + +<li>After the <code>onCreate()</code> method, add the String array: +<pre> +static final String[] COUNTRIES = new String[] { + "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", + "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", + "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", + "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", + "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", + "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", + "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi", + "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde", + "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", + "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", + "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic", + "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic", + "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", + "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland", + "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia", + "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar", + "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", + "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary", + "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", + "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos", + "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", + "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", + "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova", + "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", + "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", + "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas", + "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", + "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar", + "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena", + "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon", + "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal", + "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", + "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea", + "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden", + "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas", + "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", + "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda", + "Ukraine", "United Arab Emirates", "United Kingdom", + "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", + "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara", + "Yemen", "Yugoslavia", "Zambia", "Zimbabwe" +}; +</pre> + <p>This is the list of suggestions that will be offered as the user types into the + AutoCompleteTextView.</p> +</li> + +<li>Now run it.</li> +</ol> +<p>As you type, you should see something like this:</p> +<img src="images/hello-autocomplete.png" width="150px" /> + + +<h3>References</h3> +<ul> + <li>{@link android.R.layout}</li> + <li>{@link android.widget.ArrayAdapter}</li> + <li>{@link android.widget.AutoCompleteTextView}</li> +</ul> + +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> diff --git a/docs/html/guide/tutorials/views/hello-datepicker.jd b/docs/html/guide/tutorials/views/hello-datepicker.jd new file mode 100644 index 0000000..b35d4db --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-datepicker.jd @@ -0,0 +1,149 @@ +page.title=Hello, DatePicker +@jd:body + +<p>A {@link android.widget.DatePicker} is a widget that allows the user to select a month, day and year.</p> + + +<ol> + <li>Start a new project/Activity called HelloDatePicker.</li> + <li>Open the layout file and make it like so: + <pre> +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <TextView android:id="@+id/dateDisplay" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text=""/> + + <Button android:id="@+id/pickDate" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="Change the date"/> + +</LinearLayout> +</pre> + <p>For the layout, we're using a vertical LinearLayout, with a {@link android.widget.TextView} that + will display the date and a {@link android.widget.Button} that will initiate the DatePicker dialog. + With this layout, the TextView will sit above the Button. + The text value in the TextView is set empty, as it will be filled + with the current date when our Activity runs.</p> + </li> + + <li>Open HelloDatePicker.java. Insert the following to the HelloDatePicker class: +<pre> + private TextView mDateDisplay; + private Button mPickDate; + + private int mYear; + private int mMonth; + private int mDay; + + static final int DATE_DIALOG_ID = 0; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + // capture our View elements + mDateDisplay = (TextView) findViewById(R.id.dateDisplay); + mPickDate = (Button) findViewById(R.id.pickDate); + + // add a click listener to the button + mPickDate.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + showDialog(DATE_DIALOG_ID); + } + }); + + // get the current date + final Calendar c = Calendar.getInstance(); + mYear = c.get(Calendar.YEAR); + mMonth = c.get(Calendar.MONTH); + mDay = c.get(Calendar.DAY_OF_MONTH); + + // display the current date + updateDisplay(); + } +</pre> +<p class="note"><strong>Tip:</strong> Press Ctrl(or Cmd) + Shift + O to import all needed packages.</p> + <p>We start by instantiating variables for our Views and date fields. + The <code>DATE_DIALOG_ID</code> is a static integer that uniquely identifies the Dialog. In the + <code>onCreate()</code> method, we get prepared by setting the layout and capturing the View elements. + Then we create an on-click listener for the Button, so that when it is clicked it will + show our DatePicker dialog. The <code>showDialog()</code> method will pop-up the date picker dialog + by calling the <code>onCreateDialog()</code> callback method + (which we'll define in the next section). We then create an + instance of {@link java.util.Calendar} and get the current year, month and day. Finally, we call + <code>updateDisplay()</code>—our own method (defined later) that will fill the TextView.</p> +</li> + +<li>After the <code>onCreate()</code> method, add the <code>onCreateDialog()</code> callback method +(which is called by <code>showDialog()</code>) +<pre> +@Override +protected Dialog onCreateDialog(int id) { + switch (id) { + case DATE_DIALOG_ID: + return new DatePickerDialog(this, + mDateSetListener, + mYear, mMonth, mDay); + } + return null; +} +</pre> + <p>This method is passed the identifier we gave <code>showDialog()</code> and initializes + the DatePicker to the date we retrieved from our Calendar instance.</p> +</li> + +<li>Following that, add the <code>updateDisplay()</code> method: +<pre> + // updates the date we display in the TextView + private void updateDisplay() { + mDateDisplay.setText( + new StringBuilder() + // Month is 0 based so add 1 + .append(mMonth + 1).append("-") + .append(mDay).append("-") + .append(mYear).append(" ")); + } +</pre> +<p>This uses the member date values to write the date to our TextView.</p> +</li> +<li>Finally, add a listener that will be called when the user sets a new date: +<pre> + // the callback received when the user "sets" the date in the dialog + private DatePickerDialog.OnDateSetListener mDateSetListener = + new DatePickerDialog.OnDateSetListener() { + + public void onDateSet(DatePicker view, int year, + int monthOfYear, int dayOfMonth) { + mYear = year; + mMonth = monthOfYear; + mDay = dayOfMonth; + updateDisplay(); + } + }; +</pre> + <p>This <code>OnDateSetListener</code> method listens for when the user is done setting the date + (clicks the "Set" button). At that time, this fires and we update our member fields with + the new date defined by the user and update our TextView by calling <code>updateDisplay()</code>.</p> +</li> + +<li>Now run it.</li> +</ol> +<p>When you press the "Change the date" button, you should see the following:</p> +<img src="images/hello-datepicker.png" width="150px" /> + +<h3>References</h3> +<ul> +<li>{@link android.widget.DatePicker}</li> +<li>{@link android.widget.Button}</li> +<li>{@link android.widget.TextView}</li> +<li>{@link java.util.Calendar}</li> +</ul> +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> diff --git a/docs/html/guide/tutorials/views/hello-formstuff.jd b/docs/html/guide/tutorials/views/hello-formstuff.jd new file mode 100644 index 0000000..80ae6ce --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-formstuff.jd @@ -0,0 +1,261 @@ +page.title=Hello, Form Stuff +@jd:body + +<p>This page introduces a variety of widgets, like image buttons, +text fields, checkboxes and radio buttons.</p> + + +<ol> + <li>Start a new project/Activity called HelloFormStuff.</li> + <li>Your layout file should have a basic LinearLayout: + <pre> +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="vertical" + android:layout_width="fill_parent" + android:layout_height="fill_parent" > + +</LinearLayout> +</pre> + <p>For each widget you want to add, just put the respective View inside here.</p> +</li> +</ol> +<p class="note"><strong>Tip:</strong> As you add new Android code, press Ctrl(or Cmd) + Shift + O +to import all needed packages.</p> + + +<h2>ImageButton</h2> +<p>A button with a custom image on it. +We'll make it display a message when pressed.</p> +<ol> + <li><img src="images/android.png" align="right"/> + Drag the Android image on the right (or your own image) into the + res/drawables/ directory of your project. + We'll use this for the button.</li> + <li>Open the layout file and, inside the LinearLayout, add the {@link android.widget.ImageButton} element: +<pre> +<ImageButton + android:id="@+id/android_button" + android:layout_width="100dip" + android:layout_height="wrap_content" + android:src="@drawable/android" /> +</pre> + <p>The source of the button + is from the res/drawables/ directory, where we've placed the android.png.</p> + <p class="note"><strong>Tip:</strong> You can also reference some of the many built-in + images from the Android {@link android.R.drawable} resources, + like <code>ic_media_play</code>, for a "play" button image. To do so, change the source + attribute to <code>android:src="@android:drawable/ic_media_play"</code>.</p> +</li> +<li>To make the button to actually do something, add the following +code at the end of the <code>onCreate()</code> method: +<pre> +ImageButton button = (ImageButton) findViewById(R.id.android_button); +button.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + // Perform action on clicks + Toast.makeText(HelloFormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show(); + } +}); +</pre> +<p>This captures our ImageButton from the layout, then adds an on-click listener to it. +The {@link android.view.View.OnClickListener} must define the <code>onClick()</code> method, which +defines the action to be made when the button is clicked. Here, we show a +{@link android.widget.Toast} message when clicked.</p> +</li> +<li>Run it.</li> +</ol> + + +<h2>EditText</h2> +<p>A text field for user input. We'll make it display the text entered so far when the "Enter" key is pressed.</p> + +<ol> + <li>Open the layout file and, inside the LinearLayout, add the {@link android.widget.EditText} element: +<pre> +<EditText + android:id="@+id/edittext" + android:layout_width="fill_parent" + android:layout_height="wrap_content"/> +</pre> +</li> +<li>To do something with the text that the user enters, add the following code +to the end of the <code>onCreate()</code> method: +<pre> +EditText edittext = (EditText) findViewById(R.id.edittext); +edittext.setOnKeyListener(new OnKeyListener() { + public boolean onKey(View v, int keyCode, KeyEvent event) { + if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { + // Perform action on key press + Toast.makeText(HelloImageButton.this, edittext.getText(), Toast.LENGTH_SHORT).show(); + return true; + } + return false; + } +}); +</pre> +<p>This captures our EditText element from the layout, then adds an on-key listener to it. +The {@link android.view.View.OnKeyListener} must define the <code>onKey()</code> method, which +defines the action to be made when a key is pressed. In this case, we want to listen for the +Enter key (when pressed down), then pop up a {@link android.widget.Toast} message with the +text from the EditText field. Be sure to return <var>true</var> after the event is handled, +so that the event doesn't bubble-up and get handled by the View (which would result in a +carriage return in the text field).</p> +<li>Run it.</li> +</ol> + + +<h2>CheckBox</h2> +<p>A checkbox for selecting items. We'll make it display the the current state when pressed.</p> + +<ol> + <li>Open the layout file and, inside the LinearLayout, add the {@link android.widget.CheckBox} element: +<pre> +<CheckBox android:id="@+id/checkbox" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="check it out" /> +</pre> +</li> +<li>To do something when the state is changed, add the following code +to the end of the <code>onCreate()</code> method: +<pre> +final CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox); +checkbox.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + // Perform action on clicks + if (checkbox.isChecked()) { + Toast.makeText(HelloImageButton.this, "Selected", Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(HelloImageButton.this, "Not selected", Toast.LENGTH_SHORT).show(); + } + } +}); +</pre> +<p>This captures our CheckBox element from the layout, then adds an on-click listener to it. +The {@link android.view.View.OnClickListener} must define the <code>onClick()</code> method, which +defines the action to be made when the checkbox is clicked. Here, we query the current state of the +checkbox, then pop up a {@link android.widget.Toast} message that displays the current state. +Notice that the CheckBox handles its own state change between checked and un-checked, so we just +ask which it currently is.</p> +<li>Run it.</li> +</ol> +<p class="note"><strong>Tip:</strong> If you find that you need to change the state +in another way (such as when loading a saved {@link android.preference.CheckBoxPreference}), +use <code>setChecked(true)</code> or <code>toggle()</code>.</p> + + +<h2>RadioButton</h2> +<p>Two mutually-exclusive radio buttons—enabling one disables the other. +When each is pressed, we'll pop up a message.</p> + +<ol> + <li>Open the layout file and, inside the LinearLayout, add two {@link android.widget.RadioButton}s, +inside a {@link android.widget.RadioGroup}: +<pre> +<RadioGroup + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <RadioButton android:id="@+id/radio_red" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="Red" /> + + <RadioButton android:id="@+id/radio_blue" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="Blue" /> + +</RadioGroup> +</pre> +</li> +<li>To do something when each is selected, we'll need an OnClickListener. Unlike the other +listeners we've created, instead of creating this one as an anonymous inner class, +we'll create it as a new object. This way, we can re-use the OnClickLIstener for +both RadioButtons. So, add the following code in the HelloFormStuff Activity +(<em>outside</em> the <code>onCreate()</code> method): +<pre> +OnClickListener radio_listener = new OnClickListener() { + public void onClick(View v) { + // Perform action on clicks + RadioButton rb = (RadioButton) v; + Toast.makeText(HelloImageButton.this, rb.getText(), Toast.LENGTH_SHORT).show(); + } +}; +</pre> +<p>Our <code>onClick()</code> method will be handed the View clicked, so the first thing to do +is cast it into a RadioButton. Then we pop up a +{@link android.widget.Toast} message that displays the selection.</p> +<li>Now, at the bottom of the <code>onCreate()</code> method, add the following: +<pre> + final RadioButton radio_red = (RadioButton) findViewById(R.id.radio_red); + final RadioButton radio_blue = (RadioButton) findViewById(R.id.radio_blue); + radio_red.setOnClickListener(radio_listener); + radio_blue.setOnClickListener(radio_listener); +</pre> +<p>This captures each of the RadioButtons from our layout and adds the newly-created +OnClickListener to each.</p> +<li>Run it.</li> +</ol> +<p class="note"><strong>Tip:</strong> If you find that you need to change the state of a +RadioButton in another way (such as when loading a saved {@link android.preference.CheckBoxPreference}), +use <code>setChecked(true)</code> or <code>toggle()</code>.</p> + + +<h2>ToggleButton</h2> +<p>A button used specifically for toggling something on and off.</p> + +<ol> + <li>Open the layout file and, inside the LinearLayout, add the {@link android.widget.ToggleButton} element: +<pre> +<ToggleButton android:id="@+id/togglebutton" + android:layout_width="wrap_content" + android:layout_height="wrap_content" /> +</pre> +</li> +<li>To do something when the state is changed, add the following code +to the end of the <code>onCreate()</code> method: +<pre> +final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton); +togglebutton.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + // Perform action on clicks + if (togglebutton.isChecked()) { + Toast.makeText(HelloImageButton.this, "ON", Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(HelloImageButton.this, "OFF", Toast.LENGTH_SHORT).show(); + } + } +}); +</pre> +<p>This captures our ToggleButton element from the layout, then adds an on-click listener to it. +The {@link android.view.View.OnClickListener} must define the <code>onClick()</code> method, which +defines the action to be made when the button is clicked. Here, we query the current state of the +ToggleButton, then pop up a {@link android.widget.Toast} message that displays the current state. +Notice that the ToggleButton handles its own state change between checked and un-checked, so we just +ask which it is.</p> +<li>Run it.</li> +</ol> + +<p class="note"><strong>Tip:</strong> By default, the text on the button is "ON" and "OFF", but +you can change each of these with <code>setTextOn(<var>CharSequence</var>)</code> and +<code>setTextOff(<var>CharSequence</var>)</code>. And, if you find that you need to change the state +in another way (such as when loading a saved {@link android.preference.CheckBoxPreference}), +use <code>setChecked(true)</code> or <code>toggle()</code>. </p> + + +<p>If you've added all the form items above, your application should look something like this:</p> +<img src="images/hello-formstuff.png" width="150px" /> + +<h3>References</h3> +<ul> + <li>{@link android.widget.ImageButton}</li> + <li>{@link android.widget.EditText}</li> + <li>{@link android.widget.CheckBox}</li> + <li>{@link android.widget.RadioButton}</li> + <li>{@link android.widget.ToggleButton}</li> +</ul> + +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> diff --git a/docs/html/guide/tutorials/views/hello-gallery.jd b/docs/html/guide/tutorials/views/hello-gallery.jd new file mode 100644 index 0000000..af01757 --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-gallery.jd @@ -0,0 +1,133 @@ +page.title=Hello, Gallery +@jd:body + +<p>A {@link android.widget.Gallery} is a View commonly used to display items in a horizontally scrolling list +that locks the current selection at the center. When one is selected, we'll show a message.</p> + + +<ol> + <li>Start a new project/Activity called HelloGallery.</li> + <li>Add some images to your res/drawable/ directory.</li> + <li>Open the layout file and make it like so: +<pre> +<?xml version="1.0" encoding="utf-8"?> +<Gallery xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/gallery" + android:layout_width="fill_parent" + android:layout_height="wrap_content" +/> +</pre> +</li> + + +<li>Open the HelloGallery.java file. Insert the following for the <code>onCreate()</code> method: +<pre> +@Override +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + Gallery g = (Gallery) findViewById(R.id.gallery); + g.setAdapter(new ImageAdapter(this)); + + g.setOnItemClickListener(new OnItemClickListener() { + public void onItemClick(AdapterView parent, View v, int position, long id) { + Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show(); + } + }); +} +</pre> + <p>We start as usual: set the layout and capture the View we want (our Gallery). +We then set an Adapter, called ImageAdapter for the Gallery—this is a new class that +we'll create next. Then we create an item click listener for the Gallery. This is like a normal +on-click listener (which you might be familiar with for buttons), but it listens to each item +that we've added to the Gallery. The <code>onItemClick()</code> callback method +receives the AdapterView where the click occurred, the specific View that received the click, the +position of the View clicked (zero-based), and the row id of the item clicked (if applicable). All +that we care about is the position, so that we can pop up a {@link android.widget.Toast} message that +tells us the index position of the item clicked. We do this with <code>Toast.makeText().show()</code>. +</p> +</li> + +<li>After the <code>onCreate()</code> method, add the <code>ImageAdapter</code> class: +<pre> +public class ImageAdapter extends BaseAdapter { + int mGalleryItemBackground; + private Context mContext; + + private Integer[] mImageIds = { + R.drawable.sample_1, + R.drawable.sample_2, + R.drawable.sample_3, + R.drawable.sample_4, + R.drawable.sample_5, + R.drawable.sample_6, + R.drawable.sample_7 + }; + + public ImageAdapter(Context c) { + mContext = c; + TypedArray a = obtainStyledAttributes(android.R.styleable.Theme); + mGalleryItemBackground = a.getResourceId( + android.R.styleable.Theme_galleryItemBackground, 0); + a.recycle(); + } + + public int getCount() { + return mImageIds.length; + } + + public Object getItem(int position) { + return position; + } + + public long getItemId(int position) { + return position; + } + + public View getView(int position, View convertView, ViewGroup parent) { + ImageView i = new ImageView(mContext); + + i.setImageResource(mImageIds[position]); + i.setLayoutParams(new Gallery.LayoutParams(150, 100)); + i.setScaleType(ImageView.ScaleType.FIT_XY); + i.setBackgroundResource(mGalleryItemBackground); + + return i; + } +} +</pre> +<p>First, there are a few member variables, including an array of IDs that reference +the images we placed in our drawable resources directory.</p> +<p>Next is the constructor, where we define the member Context. The rest of the constructor +sets up a reference for our Gallery them, which adds the nice framing for each Gallery item. +Once we have our <code>mGalleryItemBackground</code>, it's important to recycle the +StyledAttribute for later re-use.</p> +<p>The next three methods are required for basic member queries. +But then we have the <code>getView()</code> method, which is called +for each item read by our ImageAdapter, when the Gallery is being built. Here, we +use our member Context to create a new {@link android.widget.ImageView}. We then define +the image resource with the current position of the Gallery items (corresponding to our +array of drawables), set the dimensions for the ImageView, +set the image scaling to fit the ImageView dimensions, then finally set the +background theme for the ImageView.</p> + +<p>See {@link android.widget.ImageView.ScaleType} +for other image scaling options, in case you want to avoid stretching images that don't +exactly match the ImageView dimensions.</p> + +<li>Now run it.</li> +</ol> +<p>You should see something like this:</p> +<img src="images/hello-gallery.png" width="150px" /> + + +<h3>References</h3> +<ul> + <li>{@link android.widget.BaseAdapter}</li> + <li>{@link android.widget.Gallery}</li> + <li>{@link android.widget.ImageView}</li> + <li>{@link android.widget.Toast}</li> +</ul> +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> + diff --git a/docs/html/guide/tutorials/views/hello-gridview.jd b/docs/html/guide/tutorials/views/hello-gridview.jd new file mode 100644 index 0000000..d5c8628 --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-gridview.jd @@ -0,0 +1,127 @@ +page.title=Hello, GridView +@jd:body + +<p>A {@link android.widget.GridView} displays items in a two-dimensional, scrolling grid. The items +are acquired from a {@link android.widget.ListAdapter}.</p> + + +<ol> + <li>Start a new project/Activity called HelloGridView.</li> + <li>Find some photos you'd like to use, or copy some from the SDK samples res/drawable/ + folder of your project.</li> + <li>Open the layout and make it like so: +<pre> +<?xml version="1.0" encoding="utf-8"?> +<GridView xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/gridview" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:numColumns="auto_fit" + android:verticalSpacing="10dp" + android:horizontalSpacing="10dp" + android:columnWidth="90dp" + android:stretchMode="columnWidth" + android:gravity="center" +/> +</li> + <li>Open the HelloGridView Java file. Insert the following for the <code>onCreate()</code> method: +<pre> +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + GridView gridview = (GridView) findViewById(R.id.gridview); + gridview.setAdapter(new ImageAdapter(this)); +} +</pre> + <p>Here, we get a handle on our GridView, from the layout, and give it an Adapter. + We're actually going to create our own Adapter called ImageAdapter.</p> +</li> +<li>Create a new class (nested or otherwise), called ImageAdapter, which extends {@link android.widget.BaseAdapter}: +<pre> +public class ImageAdapter extends BaseAdapter { + private Context mContext; + + public ImageAdapter(Context c) { + mContext = c; + } + + public int getCount() { + return mThumbIds.length; + } + + public Object getItem(int position) { + return null; + } + + public long getItemId(int position) { + return 0; + } + + // create a new ImageView for each item referenced by the Adapter + public View getView(int position, View convertView, ViewGroup parent) { + ImageView imageView; + if (convertView == null) { // if it's not recycled, initialize some attributes + imageView = new ImageView(mContext); + imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); + imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); + imageView.setPadding(8, 8, 8, 8); + } else { + imageView = (ImageView) convertView; + } + + imageView.setImageResource(mThumbIds[position]); + return imageView; + } + + // references to our images + private Integer[] mThumbIds = { + R.drawable.sample_2, R.drawable.sample_3, + R.drawable.sample_4, R.drawable.sample_5, + R.drawable.sample_6, R.drawable.sample_7, + R.drawable.sample_0, R.drawable.sample_1, + R.drawable.sample_2, R.drawable.sample_3, + R.drawable.sample_4, R.drawable.sample_5, + R.drawable.sample_6, R.drawable.sample_7, + R.drawable.sample_0, R.drawable.sample_1, + R.drawable.sample_2, R.drawable.sample_3, + R.drawable.sample_4, R.drawable.sample_5, + R.drawable.sample_6, R.drawable.sample_7 + }; +} +</pre> + <p>First we take care of some required methods inherited from BaseAdapter. + The constructor and <code>getCount()</code> are self-explanitory. Normally, <code>getItem()</code> + should return the actual object at the specified position in our Adapter, but for this Hello World, + we're not going to bother. Likewise, <code>getItemId()</code> should return the row id of + the item, but right now we don't care.</p> + <p>However, <code>getView()</code> is the method we care about. This one creates a new View for each image that we + put in our ImageAdapter. So we're going to create an ImageView each time. When this is called, we're + going to receive a View, which is likely a recycled View object (at least after the first call), so we + check for this—if it's null, we initialize the ImageView and setup all the properties we want. + The <code>LayoutParams()</code> initialization sets the height and width of the View—this ensures + that no matter the drawable size, each image is resized and cropped to fit in the ImageView (if necessary). + With <code>setScaleType()</code>, we say that images should be cropped toward the center (if necessary). + And finally, we set the padding within the ImageView. (Note that, if the images have various aspect-ratios, + as they do in this demo, then less padding will cause for more cropping of the image, if it does not match + the dimensions given to the ImageView.) At the end of <code>getView()</code> we set the image resource and + return the ImageView.</p> + <p>All that's left is our array or drawable resources at the bottom.</p> +</li> +<li>Run it.</li> +</ol> +<p>Your grid layout should look something like this:</p> +<img src="images/hello-gridview.png" width="150px" /> + +<p>Try experimenting with the behaviors of the GridView and ImageView by adjusting their properties. For example, + instead of setting the ImageView LayoutParams, you can try using + {@link android.widget.ImageView#setAdjustViewBounds(boolean)}. </p> + +<h3>References</h3> +<ul> + <li>{@link android.widget.GridView}</li> + <li>{@link android.widget.ImageView}</li> + <li>{@link android.widget.BaseAdapter}</li> +</ul> + +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> diff --git a/docs/html/guide/tutorials/views/hello-linearlayout.jd b/docs/html/guide/tutorials/views/hello-linearlayout.jd new file mode 100644 index 0000000..ecea062 --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-linearlayout.jd @@ -0,0 +1,128 @@ +page.title=Hello, LinearLayout +@jd:body + +<p>A {@link android.widget.LinearLayout} is a GroupView that will lay child View elements +vertically or horizontally.</p> + + +<ol> + <li>Start a new project/Activity called HelloLinearLayout.</li> + <li>Open the layout file. + Make it like so: +<pre> +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="vertical" + android:layout_width="fill_parent" + android:layout_height="fill_parent"> + + <LinearLayout + android:orientation="horizontal" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:layout_weight="1"> + + <TextView + android:text="red" + android:gravity="center_horizontal" + android:background="#aa0000" + android:layout_width="wrap_content" + android:layout_height="fill_parent" + android:layout_weight="1"/> + + <TextView + android:text="green" + android:gravity="center_horizontal" + android:background="#00aa00" + android:layout_width="wrap_content" + android:layout_height="fill_parent" + android:layout_weight="1"/> + + <TextView + android:text="blue" + android:gravity="center_horizontal" + android:background="#0000aa" + android:layout_width="wrap_content" + android:layout_height="fill_parent" + android:layout_weight="1"/> + + <TextView + android:text="yellow" + android:gravity="center_horizontal" + android:background="#aaaa00" + android:layout_width="wrap_content" + android:layout_height="fill_parent" + android:layout_weight="1"/> + + </LinearLayout> + + <LinearLayout + android:orientation="vertical" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:layout_weight="1"> + + <TextView + android:text="row one" + android:textSize="15pt" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:layout_weight="1"/> + + <TextView + android:text="row two" + android:textSize="15pt" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:layout_weight="1"/> + + <TextView + android:text="row three" + android:textSize="15pt" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:layout_weight="1"/> + + <TextView + android:text="row four" + android:textSize="15pt" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:layout_weight="1"/> + + </LinearLayout> + +</LinearLayout> +</pre> + <p>Carefully inspect the XML. You'll notice how this layout works a lot like + an HTML layout. There is one parent LinearLayout that is defined to lay + its child elements vertically. The first child is another LinearLayout that uses a horizontal layout + and the second uses a vertical layout. Each LinearLayout contains several {@link android.widget.TextView} + elements.</p> +</li> +<li>Now open the HelloLinearLayout Activity and be sure it loads this layout in the <code>onCreate()</code> method:</p> +<pre> +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); +} +</pre> +<p><code>R.layout.main</code> refers to the <code>main.xml</code> layout file.</p> +</li> +<li>Run it.</li> +</ol> +<p>You should see the following:</p> +<img src="images/hello-linearlayout.png" width="150px" /> + +<p>Notice how the various XML attributes define the View's behavior. +Pay attention to the effect of the <code>layout_weight</code>. Try + experimenting with different values to see how the screen real estate is + distributed based on the weight of each element.</p> + +<h3>References</h3> +<ul> + <li>{@link android.widget.LinearLayout}</li> +<li>{@link android.widget.TextView}</li> +</ul> + +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> diff --git a/docs/html/guide/tutorials/views/hello-listview.jd b/docs/html/guide/tutorials/views/hello-listview.jd new file mode 100644 index 0000000..41b7f6e --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-listview.jd @@ -0,0 +1,89 @@ +page.title=Hello, ListView +@jd:body + +<p>A {@link android.widget.ListView} is a View that shows items in a vertically scrolling list. The items are + acquired from a {@link android.widget.ListAdapter}.</p> + + +<ol> + <li>Start a new project/ListActivity called HelloListView.</li> + <li>Open the HelloListView Java file. Make the class extend ListActivity (instead of Activity). + <pre>public class HelloListView extends ListActivity {</pre> + </li> + <li>Insert the following for the <code>onCreate()</code> method: +<pre> +@Override +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setListAdapter(new ArrayAdapter<String>(this, + android.R.layout.simple_list_item_1, COUNTRIES)); + getListView().setTextFilterEnabled(true); +} +</pre> + <p>Notice that we don't need to load a layout (at least, not in this case, because we're using + the whole screen for our list). Instead, we just call <code>setListAdapter()</code> (which automatically + adds a ListView to the ListActivity), and provide it with an ArrayAdapter that binds a + <code>simple_list_item_1</code> layout item to each entry in the <code>COUNTRIES</code> + array (added next). The next line of code adds a text filter to the ListView, so that when the user + begins typing, the list will filter the entire view to display only the items that match the entry.</p> + </li> + <li>Following the <code>onCreate()</code> method, add the String array: +<pre> + static final String[] COUNTRIES = new String[] { + "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", + "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", + "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", + "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", + "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", + "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", + "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi", + "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde", + "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", + "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", + "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic", + "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic", + "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", + "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland", + "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia", + "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar", + "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", + "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary", + "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", + "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos", + "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", + "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", + "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova", + "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", + "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", + "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas", + "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", + "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar", + "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena", + "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon", + "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal", + "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", + "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea", + "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden", + "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas", + "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", + "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda", + "Ukraine", "United Arab Emirates", "United Kingdom", + "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", + "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara", + "Yemen", "Yugoslavia", "Zambia", "Zimbabwe" + }; +</pre> +</li> +<li> Run it.</li> +</ol> +<p>You can scroll the list, or type to filter it. You should see something like this:</p> +<img src="images/hello-listview.png" width="150px" /> + +<h3>References</h3> +<ul> + <li>{@link android.widget.ListView}</li> + <li>{@link android.widget.ListAdapter}</li> +</ul> + +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> diff --git a/docs/html/guide/tutorials/views/hello-mapview.jd b/docs/html/guide/tutorials/views/hello-mapview.jd new file mode 100644 index 0000000..5b23f9b --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-mapview.jd @@ -0,0 +1,231 @@ +page.title=Hello, MapView +@jd:body + +<p>A MapView allows you to create your own map-viewing Activity. +First, we'll create a simple Activity that can view and navigate a map. Then we will add some overlay items.</p> + +<ol> + <li>Start a new project/Activity called HelloMapView. + + <li>Because we're using the Google Maps library, + which is not a part of the standard Android library, we need to + declare it in the Android Manifest. Open the AndroidManifest.xml + file and add the following as a child of the <code><application></code> element: + + <pre><uses-library android:name="com.google.android.maps" /></pre> + </li> + + <li>Open the layout file. Define the layout with a MapView inside a RelativeLayout: + +<pre> +<?xml version="1.0" encoding="utf-8"?> +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/mainlayout" + android:orientation="vertical" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + > + + <com.google.android.maps.MapView + android:id="@+id/mapview" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:clickable="true" + android:apiKey="myapikey" + /> + +<RelativeLayout> +</pre> + + <p>The <code>android:apiKey</code> should actually contain a legitimate value that's + associated to your application. For now, it's okay to just leave this as an + arbitrary string. But to run on 1.0 software, an authentic key will be needed.</p></li> + + <li>Now open the HelloMapView.java file. For this Activity, we're going to extend the special sub-class of + Activity called MapActivity, so change the class declaration to extend + MapActicity, instead of Activity:</p> + + <pre>public class HelloMapView extends MapActivity {</pre> + + <li>The <code>isRouteDisplayed()</code> method is requires, so add it inside the class: +<pre> +@Override +protected boolean isRouteDisplayed() { + return false; +} +</pre> +<p>You can actually run this now, but all it does is allow you to pan around the map.</p> +<p>Android provides a handy {@link android.widget.ZoomControls} widget for zooming in and out of a View. +MapView can automatically hook one for us by requesting it with the <code>getZoomControls()</code> +method. Let's do this.</p> + +<li>Go back to the layout file. We need a new ViewGroup element, in which we'll + place the ZoomControls. Just below the MapView element (but inside the RelativeLayout), add this element: +<pre> +<LinearLayout + android:id="@+id/zoomview" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_alignBottom="@id/mapview" + android:layout_centerHorizontal="true" +/></pre> + + <p>It doesn't really matter what kind of ViewGroup we use, because we just want a + container that we can position within our root RelativeLayout.</p> + + <p>The last two attributes are available only to an element that's a child of a + RelativeLayout. <code>layout_alignBottom</code> aligns the bottom of this element to the bottom of + the element identified with a resource tag (which must be a sibling to this element). + <code>layout_centerHorizontal</code> centers this on the horizontal plane.</p></li> + + <li>Now go back to the HelloMapView class. We'll now retrieve the ZoomControls object from + the MapView and add it to our new layout element. First, at the top of the HelloMapView, + instantiate handles for the MapView and LinearLayout, plus a ZoomControl object: +<pre> +LinearLayout linearLayout; +MapView mapView; +ZoomControls mZoom;</pre></li> + + <li>Then initialize each of these in <code>onCreate()</code>. We'll capture the LinearLayout and + MapView through their layout resources. Then get the ZoomControls from the MapView:: +<pre> +linearLayout = (LinearLayout) findViewById(R.id.zoomview); +mapView = (MapView) findViewById(R.id.mapview); +mZoom = (ZoomControls) mapView.getZoomControls();</pre> + + <p>By using the ZoomControls object provided by MapView, we don't have to do any of the work + required to actually perform the zoom operations. The ZoomControls widget that MapView + returns for us is already hooked into the MapView and works as soon as we add it to the + layout. The controls will appear whenever the user touches the map, then dissapear after + a few moments of inactivity.</p></li> + + <li>Now just plug our ZoomControls into the LinearLayout we added: + + <pre>linearLayout.addView(mZoom);</pre></li> + + <li>Run it.</li> +</ol> + +<hr/> + +<p>So, we now have full interaction controls. All well and good, but what we really want our map +for is custom markers and layovers. Let's add some Overlay +objects to our map. To do this, we're going to +implement the ItemizedOverlay +class, which can manage a whole set of Overlay items for us.</p> + +<ol> + <li>Create a new Java class named HelloItemizedOverlay that implements ItemizedOverlay. + + <p>Right-click the package name in the Eclipse Package Explorer, and select New > Class. Fill-in + the Name field as <em>HelloItemizedOverlay</em>. For the Superclass, enter + <em>com.google.android.maps.ItemizedOverlay</em>. Click the checkbox for <em>Constructors from + superclass</em>. Click Finish.</p></li> + + <li> First thing, we need an OverlayItem ArrayList, in which we'll put each of the OverlayItem + objects we want on our map. Add this at the top of the HelloItemizedOverlay class: + + <pre>private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();</pre></li> + + <li>All the constructor does is define the default marker to be used on each of the OverlayItems. + In order for the Drawable to actually get drawn, it must have its bounds defined. And we want the + center-point at the bottom of the image to be the point at which it's attached to the map + coordinates. We handle all this with the boundCenterBottom() method. Wrap this around our + defaultMarker, so the super constructor call looks like this: + + <pre>super(boundCenterBottom(defaultMarker));</pre></li> + + <li>In order to add new OverlayItems to our ArrayList, we need a new public method. We'll handle + this with the following method: + +<pre> +public void addOverlay(OverlayItem overlay) { + mOverlays.add(overlay); + populate(); +}</pre> + + <p>Each time we add a new OverlayItem, we must call <code>populate()</code>, which will read each of out + OverlayItems and prepare them to be drawn.</p></li> + + <li>In order for the <code>populate()</code> method to read each OverlayItem, it will make a request to + <code>createItem(int)</code>. We must define this method to properly read from our ArrayList. Replace the + existing contents of the createItem method with a <code>get()</code> call to our ArrayList: + + <pre>return mOverlays.get(i);</pre></li> + + <li>We're also required to override the <code>size()</code> method. Replace the existing contents of the + method with a size request to our ArrayList: + + <pre>return mOverlays.size();</pre></li> +</ol> + + +<p>That's it for the HelloItemizedOverlay class. We're now ready to use it.</p> + +<hr/> +<p>Go back to the HelloMapView +class. We'll start by creating one OverlayItem, adding to an instance of our HelloItemizedOverlay, +and then adding this to the MapView.</p> + +<img src="images/androidmarker.png" align="right" /> +<p>First, we need the image that we'll use for our map overlay. Here, we'll use the Android on the +right as our marker. Drag this image (or your own) to the res/drawable/ directory of your project workspace.</p> + +<p>Now we're ready to work in the HelloMapView:</p> + +<ol> + <li>First we need some more types. Add the following at the top of the HelloMapView class: + +<pre> +List<Overlay> mapOverlays; +Drawable drawable; +HelloItemizedOverlay itemizedOverlay;</pre></li> + + <li>Now pick up where we left off in the <code>onCreate()</code> method. Instantiate the + new fields: + +<pre> +mapoverlays = mapView.getOverlays(); +drawable = this.getResources().getDrawable(R.drawable.banana); +itemizedoverlay = new HelloItemizedOverlay(drawable);</pre> + + <p>All overlay elements on a map are held by the MapView, so when we want to add some, we must + first retrieve the List with <code>getOverlays()</code> methods. We instantiate the Drawable, which will + be used as our map marker, by using our Context resources to get the Drawable we placed in + the res/drawable/ directory. Our HelloItemizedOverlay takes the Drawable in order to set the + default marker.</p></li> + + <li>Now let's make our first OverlayItem by creating a GeoPoint + that defines our map coordinates, then pass it to a new OverlayItem: + +<pre> +GeoPoint point = new GeoPoint(19240000,-99120000); +OverlayItem overlayitem = new OverlayItem(point, "", "");</pre> + + <p>GeoPoint coordinates are based in microdegrees (degrees * 1e6). The OverlayItem takes this + GeoPoint and two strings. Here, we won't concern ourselves with the strings, which can display + text when we click our marker, because we haven't yet written the click handler for the OverlayItem.</p></li> + + <li>All that's left is for us to add this OverlayItem to our collection in the HelloItemizedOverlay, + and add this to the List of Overlay objects retrieved from the MapView: + +<pre> +itemizedoverlay.addOverlay(overlayitem); +mapoverlays.add(itemizedoverlay);</pre></li> + + <li>Run it!</li> +</ol> + +<p>We've sent our droid to Mexico City. Hola, Mundo!</p> +<p>You should see the following:</p> +<img src="images/hello-mapview.png" width="150px" /> + +<p>Because we created our ItemizedOverlay class with an ArrayList, we can continue adding new +OverlayItems. Try adding another one. Before the <code>addOverlay()</code> method is called, add these lines:</p> +<pre> +GeoPoint point2 = new GeoPoint(35410000, 139460000); +OverlayItem overlayitem2 = new OverlayItem(point2, "", ""); +</pre> +<p>Run it again... We've sent a new droid to Tokyo. Sekai, konichiwa!</p> + +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> diff --git a/docs/html/guide/tutorials/views/hello-relativelayout.jd b/docs/html/guide/tutorials/views/hello-relativelayout.jd new file mode 100644 index 0000000..4467631 --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-relativelayout.jd @@ -0,0 +1,77 @@ +page.title=Hello, RelativeLayout +@jd:body + +<p>A {@link android.widget.RelativeLayout} is a ViewGroup that allows you to layout child elements +in positions relative to the parent or siblings elements.</p> + +<ol> + <li>Start a new project/Activity called HelloRelativeLayout.</li> + <li>Open the layout file. Make it like so: +<pre> +<?xml version="1.0" encoding="utf-8"?> +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="fill_parent" + android:layout_height="fill_parent"> + + <TextView + android:id="@+id/label" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:text="Type here:"/> + + <EditText + android:id="@+id/entry" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:background="@android:drawable/editbox_background" + android:layout_below="@id/label"/> + + <Button + android:id="@+id/ok" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_below="@id/entry" + android:layout_alignParentRight="true" + android:layout_marginLeft="10dip" + android:text="OK" /> + + <Button + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_toLeftOf="@id/ok" + android:layout_alignTop="@id/ok" + android:text="Cancel" /> + +</RelativeLayout> +</pre> +<p>Pay attention to each of the additional <code>layout_*</code> attributes (besides the +usual width and height, which are required for all elements). When using relative layout, +we use attributes like <code>layout_below</code> and <code>layout_toLeftOf</code> to describe +how we'd like to position each View. Naturally, these are different relative positions, and the +value of the attribute is the id of the element we want the position relative to.</p> +</li> +<li>Make sure your Activity loads this layout in the <code>onCreate()</code> method:</p> +<pre> +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); +} +</pre> +<p><code>R.layout.main</code> refers to the <code>main.xml</code> layout file.</p> +</li> +<li>Run it.</li> +</ol> +<p>You should see the following:</p> +<img src="images/hello-relativelayout.png" width="150px" /> + +<h3>Resources</h3> +<ul> + <li>{@link android.widget.RelativeLayout}</li> + <li>{@link android.widget.TextView}</li> + <li>{@link android.widget.EditText}</li> + <li>{@link android.widget.Button}</li> +</ul> + + +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> + diff --git a/docs/html/guide/tutorials/views/hello-spinner.jd b/docs/html/guide/tutorials/views/hello-spinner.jd new file mode 100644 index 0000000..4a0f12f --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-spinner.jd @@ -0,0 +1,105 @@ +page.title=Hello, Spinner +@jd:body + +<p>A {@link android.widget.Spinner} is a widget that allows the user to select an item from a group. +It is similar to a dropdown list and will allow scrolling when the +list exceeds the available vertical space on the screen.</p> + + +<ol> + <li>Start a new project/Activity called HelloSpinner.</li> + <li>Open the layout file. + Make it like so: +<pre> +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:orientation="vertical" + android:padding="10dip" + android:layout_width="fill_parent" + android:layout_height="wrap_content"> + + <TextView + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:layout_marginTop="10dip" + android:text="Please select a planet:" + /> + + <Spinner + android:id="@+id/spinner" + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:drawSelectorOnTop="true" + android:prompt="@string/planet_prompt" + /> + +</LinearLayout> +</pre> + <p>Notice that the Spinner's <code>android:prompt</code> is a string resource. In + this case, Android does not allow it to be a string, it must be a reference to a resource. + So...</p> +</li> + +<li>Open the strings.xml file in res/values/ and add the following <code><string></code> +element inside the <code><resources></code> element: +<pre> +<string name="planet_prompt">Choose a planet</string> +</pre> +</li> + +<li>Create a new XML file in res/values/ called arrays.xml. Insert the following: +<pre> +<resources> + + <string-array name="planets"> + <item>Mercury</item> + <item>Venus</item> + <item>Earth</item> + <item>Mars</item> + <item>Jupiter</item> + <item>Saturn</item> + <item>Uranus</item> + <item>Neptune</item> + </string-array> + +</resources> +</pre> + <p>This is the list of items (planets) that the user can select from in the Spinner widget.</p> +</li> + +<li>Now open the HelloSpinner.java file. Insert the following code into the HelloSpinner class: +<pre> +@Override +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + Spinner s = (Spinner) findViewById(R.id.spinner); + ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( + this, R.array.planets, android.R.layout.simple_spinner_item); + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + s.setAdapter(adapter); +} +</pre> + <p>That's it. We start by creating a Spinner from our layout. We then create an {@link android.widget.ArrayAdapter} + that binds each element of our string array to a layout view—we pass <code>createFromResource</code> our Context, + the array of selectable items and the type of layout we'd like each one bound to. We then call + <code>setDropDownViewResource()</code> to define the type of layout in which to present the + entire collection. Finally, we set this Adapter to associate with our Spinner, + so the string items have a place to go.</p> +</li> + +<li>Now run it.</li> +</ol> +<p>It should look like this:</p> +<img src="images/hello-spinner.png" width="150px" /> + + +<h3>Resources</h3> +<ul> + <li>{@link android.R.layout}</li> + <li>{@link android.widget.ArrayAdapter}</li> + <li>{@link android.widget.Spinner}</li> +</ul> + +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> diff --git a/docs/html/guide/tutorials/views/hello-tablelayout.jd b/docs/html/guide/tutorials/views/hello-tablelayout.jd new file mode 100644 index 0000000..e7f2de5 --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-tablelayout.jd @@ -0,0 +1,119 @@ +page.title=Hello, TableLayout +@jd:body + +<p>A {@link android.widget.TableLayout} is a ViewGroup that +will lay child View elements into rows and columns.</p> + + +<ol> + <li>Start a new project/Activity called HelloTableLayout.</li> + <li>Open the layout file. + Make it like so: +<pre> +<?xml version="1.0" encoding="utf-8"?> +<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + android:stretchColumns="1"> + + <TableRow> + <TextView + android:layout_column="1" + android:text="Open..." + android:padding="3dip" /> + <TextView + android:text="Ctrl-O" + android:gravity="right" + android:padding="3dip" /> + </TableRow> + + <TableRow> + <TextView + android:layout_column="1" + android:text="Save..." + android:padding="3dip" /> + <TextView + android:text="Ctrl-S" + android:gravity="right" + android:padding="3dip" /> + </TableRow> + + <TableRow> + <TextView + android:layout_column="1" + android:text="Save As..." + android:padding="3dip" /> + <TextView + android:text="Ctrl-Shift-S" + android:gravity="right" + android:padding="3dip" /> + </TableRow> + + <View + android:layout_height="2dip" + android:background="#FF909090" /> + + <TableRow> + <TextView + android:text="X" + android:padding="3dip" /> + <TextView + android:text="Import..." + android:padding="3dip" /> + </TableRow> + + <TableRow> + <TextView + android:text="X" + android:padding="3dip" /> + <TextView + android:text="Export..." + android:padding="3dip" /> + <TextView + android:text="Ctrl-E" + android:gravity="right" + android:padding="3dip" /> + </TableRow> + + <View + android:layout_height="2dip" + android:background="#FF909090" /> + + <TableRow> + <TextView + android:layout_column="1" + android:text="Quit" + android:padding="3dip" /> + </TableRow> +</TableLayout> +</pre> +<p>Notice how this resembles the structure of an HTML table. <code>TableLayout</code> is like the +<code>table</code> element; <code>TableRow</code> is like a <code>tr</code> element; but for our cells like +the html <code>td</code> element, we can use any kind of View. Here, we use <code>TextView</code> for the cells.</p> + +</li> +<li>Make sure your Activity loads this layout in the <code>onCreate()</code> method: +<pre> +public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); +} +</pre> +<p><code>R.layout.main</code> refers to the <code>main.xml</code> layout file.</p> +</li> +<li>Run it.</li> +</ol> +<p>You should see the following:</p> +<img src="images/hello-tablelayout.png" width="150px" /> + +<h3>References</h3> +<ul> + <li>{@link android.widget.TableLayout}</li> + <li>{@link android.widget.TableRow}</li> + <li>{@link android.widget.TextView}</li> +</ul> + + +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> + + diff --git a/docs/html/guide/tutorials/views/hello-timepicker.jd b/docs/html/guide/tutorials/views/hello-timepicker.jd new file mode 100644 index 0000000..2faad00 --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-timepicker.jd @@ -0,0 +1,157 @@ +page.title=Hello, TimePicker +@jd:body + +<p>A {@link android.widget.TimePicker} is a widget that allows the +user to select the time by hour, minute and AM or PM.</p> + + +<ol> + <li>Start a new project/Activity called HelloTimePicker.</li> + <li>Open the layout file and make it like so: + <pre> +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <TextView android:id="@+id/timeDisplay" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text=""/> + + <Button android:id="@+id/pickTime" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="Change the time"/> + +</LinearLayout> +</pre> + <p>For the layout, we're using a vertical LinearLayout, with a {@link android.widget.TextView} that + will display the time and a {@link android.widget.Button} that will initiate the + {@link android.widget.TimePicker} dialog. + With this layout, the TextView will sit above the Button. + The text value in the TextView is set empty, as it will be filled by our Activity + with the current time.</p> + </li> + + <li>Open HelloTimePicker.java. Insert the following to the HelloTimePicker class: +<pre> +private TextView mTimeDisplay; +private Button mPickTime; + +private int mHour; +private int mMinute; + +static final int TIME_DIALOG_ID = 0; + +@Override +protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + // capture our View elements + mTimeDisplay = (TextView) findViewById(R.id.timeDisplay); + mPickTime = (Button) findViewById(R.id.pickTime); + + // add a click listener to the button + mPickTime.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + showDialog(TIME_DIALOG_ID); + } + }); + + // get the current time + final Calendar c = Calendar.getInstance(); + mHour = c.get(Calendar.HOUR_OF_DAY); + mMinute = c.get(Calendar.MINUTE); + + // display the current date + updateDisplay(); +} +</pre> +<p class="note"><strong>Tip:</strong> Press Ctrl(or Cmd) + Shift + O to import all needed packages.</p> + <p>We start by instantiating variables for our View elements and time fields. + The <code>TIME_DIALOG_ID</code> is a static integer that uniquely identifies the dialog. In the + <code>onCreate()</code> method, we get prepared by setting the layout and capturing the View elements. + We then set an on-click listener for the Button, so that when it is clicked, it will + show our TimePicker dialog. The <code>showDialog()</code> method will perform a callback + to our Activity. (We'll define this callback in the next section.) We then create an + instance of {@link java.util.Calendar} and get the current hour and minute. Finally, we call + <code>updateDisplay()</code>—our own method that will fill the TextView with the time.</p> +</li> + +<li>After the <code>onCreate()</code> method, add the <code>onCreateDialog()</code> callback method: +<pre> +@Override +protected Dialog onCreateDialog(int id) { + switch (id) { + case TIME_DIALOG_ID: + return new TimePickerDialog(this, + mTimeSetListener, mHour, mMinute, false); + } + return null; +} +</pre> + <p>This is passed the identifier we gave <code>showDialog()</code> and initializes + the TimePicker to the time we retrieved from our Calendar instance. It will be called by + <code>showDialog()</code>.</p> +</li> + +<li>Now add our <code>updateDisplay()</code> method: +<pre> +// updates the time we display in the TextView +private void updateDisplay() { + mTimeDisplay.setText( + new StringBuilder() + .append(pad(mHour)).append(":") + .append(pad(mMinute))); +} +</pre> + <p>This simply takes our member fields for the time and inserts them in + the <code>mTimeDisplay</code> TextView. Note that we call a new method, <code>pad()</code>, + on the hour and minute. (We'll create this method in the last step.)</p> +</li> + +<li>Next, add a listener to be called when the time is reset: +<pre> +// the callback received when the user "sets" the time in the dialog +private TimePickerDialog.OnTimeSetListener mTimeSetListener = + new TimePickerDialog.OnTimeSetListener() { + public void onTimeSet(TimePicker view, int hourOfDay, int minute) { + mHour = hourOfDay; + mMinute = minute; + updateDisplay(); + } + }; +</pre> + <p>Now when the user is done setting the time (clicks the "Set" button), we update our member fields with + the new time and update our TextView.</p> +</li> +<li>Finally, add the <code>pad()</code> method that we called from the <code>updateDisplay()</code>: +<pre> +private static String pad(int c) { + if (c >= 10) + return String.valueOf(c); + else + return "0" + String.valueOf(c); +} +</pre> + <p>This method returns the appropriate String representation of the hour or minute. + It will prefix a zero to the number if it's a single digit. + </p> +</li> + +<li>Now run it.</li> +</ol> +<p>When you press the "Change the time" button, you should see the following:</p> +<img src="images/hello-timepicker.png" width="150px" /> + +<h3>References</h3> +<ol> + <li>{@link android.widget.TimePicker}</li> + <li>{@link android.widget.Button}</li> + <li>{@link android.widget.TextView}</li> + <li>{@link java.util.Calendar}</li> +</ol> +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> diff --git a/docs/html/guide/tutorials/views/hello-views-index.jd b/docs/html/guide/tutorials/views/hello-views-index.jd new file mode 100644 index 0000000..fd00233 --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-views-index.jd @@ -0,0 +1,112 @@ +page.title=Hello, Views +@jd:body + +<style> +.view {float:left; margin:10px; font-size:120%; font-weight:bold;} +.view img {border:1px solid black; margin-top:5px; padding:5px;} +</style> + +<p>This collection of "Hello World"-style tutorials is designed +to get you quickly started with common Android Views and widgets. The aim is to let you copy and paste +these kinds of boring bits so you can focus on developing the code that makes your Android application rock. +Of course, we'll discuss some of the given code so that it all makes sense.</p> + +<p>Note that a certain amount of knowledge is assumed for these tutorials. If you haven't +completed the <a href="{@docRoot}guide/tutorials/hello-world.html">Hello World tutorial</a>, +please do so—it will teach you many things you should know about basic +Android development and Eclipse features. More specifically, you should know:</p> +<ul> + <li>How to create a new Android project.</li> + <li>The basic structure of an Android project (resource files, layout files, etc.).</li> + <li>The essential components of an {@link android.app.Activity}.</li> + <li>How to build and run a project.</li> +</ul> +<p>Please, also notice that, in order to make these tutorials simple, some may +not convey the better Android coding practices. In particular, many of them +use hard-coded strings in the layout files—the better practice is to reference strings from +your strings.xml file.</p> +<p>With this knowledge, you're ready to begin, so take your pick.</p> + +<div> + +<div class="view"> +<a href="hello-linearlayout.html">LinearLayout<br/> +<img src="images/hello-linearlayout.png" height="285" width="200" /></a> +</div> +<div class="view"> +<a href="hello-relativelayout.html">RelativeLayout<br/> +<img src="images/hello-relativelayout.png" height="285" width="200" /></a> +</div> +<div class="view"> +<a href="hello-tablelayout.html">TableLayout<br/> +<img src="images/hello-tablelayout.png" height="285" width="200" /></a> +</div> + +<div class="view"> +<a href="hello-datepicker.html">DatePicker<br/> +<img src="images/hello-datepicker.png" height="285" width="200" /></a> +</div> + +<div class="view"> +<a href="hello-timepicker.html">TimePicker<br/> +<img src="images/hello-timepicker.png" height="285" width="200" /></a> +</div> +<div class="view"> +<a href="hello-formstuff.html">Form Stuff<br/> +<img src="images/hello-formstuff.png" height="285" width="200" /></a> +</div> +<div class="view"> +<a href="hello-spinner.html">Spinner<br/> +<img src="images/hello-spinner.png" height="285" width="200" /></a> +</div> + +<div class="view"> +<a href="hello-autocomplete.html">AutoComplete<br/> +<img src="images/hello-autocomplete.png" height="285" width="200" /></a> +</div> +<div class="view"> +<a href="hello-listview.html">ListView<br/> +<img src="images/hello-listview.png" height="285" width="200" /></a> +</div> +<div class="view"> +<a href="hello-gridview.html">GridView<br/> +<img src="images/hello-gridview.png" height="285" width="200" /></a> +</div> + +<div class="view"> +<a href="hello-gallery.html">Gallery<br/> +<img src="images/hello-gallery.png" height="285" width="200" /></a> +</div> +<div class="view"> +<a href="hello-mapview.html">MapView<br/> +<img src="images/hello-mapview.png" height="285" width="200" /></a> +</div> + +<div class="view"> +<a href="hello-webview.html">WebView<br/> +<img src="images/hello-webview.png" height="285" width="200" /></a> +</div> + +<!-- +TODO + +<div class="view"> +<a href="hello-popupwindow.html">PopupWindow<br/> +<img src="images/hello-popupwindow.png" height="285" width="200" /></a> +</div> +<div class="view"> +<a href="hello-tabhost.html">TabHost / TabWidget<br/> +<img src="images/hello-tabhost.png" height="285" width="200" /></a> +</div> +ProgressBar; RatingBar; FrameLayout + +--> + +<p class="note" style="clear:left"> +There are plenty more Views and widgets available. See the {@link android.view.View} class +for more on View layouts, and the {@link android.widget widget package} +for more useful widgets. And for more raw code samples, visit the +<a href="{@docRoot}samples/ApiDemos/src/com/example/android/apis/view/index.html">Api Demos</a>. +These can also be found offline, in <code>/<your-SDK>/samples/ApiDemos</code>.</p> +</div> + diff --git a/docs/html/guide/tutorials/views/hello-webview.jd b/docs/html/guide/tutorials/views/hello-webview.jd new file mode 100644 index 0000000..542f91f --- /dev/null +++ b/docs/html/guide/tutorials/views/hello-webview.jd @@ -0,0 +1,117 @@ +page.title=Hello, WebView +@jd:body + +<p>A {@link android.webkit.WebView} allows you to create your own web browser Activity. In this tutorial, +we'll create a simple Activity that can view web pages.</p> + +<ol> + <li>Create a new project/Activity called HelloWebView.</li> + <li>Open the layout file. Insert a WebView so it looks like so: +<pre> +<?xml version="1.0" encoding="utf-8"?> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <WebView + android:id="@+id/webview" + android:layout_width="fill_parent" + android:layout_height="fill_parent" + /> + +</LinearLayout> +</pre></li> + + <li>Now open the HelloWebView.java file. + At the top of the class, instantiate a WebView object: +<pre>WebView webview;</pre> + <p> Then add the following at the end of the <code>onCreate()</code> method:</p> +<pre> +webview = (WebView) findViewById(R.id.webview); +webview.getSettings().setJavaScriptEnabled(true); +webview.loadUrl("http://www.google.com"); +</pre> + + <p>This captures the WebView we created in our layout, then requests a + {@link android.webkit.WebSettings} object and enables JavaScript. + Then we load a URL.</p></li> + + <li>Because we're accessing the internet, we need to add the appropriate + permissions to the Android manifest file. So open the AndroidManifest.xml file + and, add the following as a child of the <code><manifest></code> element: + + <pre><uses-permission android:name="android.permission.INTERNET" /></pre></li> + + <li>Now run it.</li> +</ol> +<p> You now have the world's simplest web page viewer. + It's not quite a browser yet. It only loads the page we've requested.</p> + +<hr/> + +<p>We can load a page, but as soon as we click a link, the default Android web browser +handles the Intent, instead of our own WebView handling the action. So now we'll +override the {@link android.webkit.WebViewClient} to enable us to handle our own URL loading.</p> + +<ol> + <li>In the HelloAndroid Activity, add this nested private class: +<pre> +private class HelloWebViewClient extends WebViewClient { + @Override + public boolean shouldOverrideUrlLoading(WebView view, String url) { + view.loadUrl(url); + return true; + } +}</pre></li> + + <li>Now, in the <code>onCreate()</code> method, set an instance of the <code>HelloWebViewClient</code> + as our WebViewClient: + <pre>webview.setWebViewClient(new WebViewClientDemo());</pre> + + <p>This line should immediately follow the initialization of our WebView object.</p> + <p>What we've done is create a WebViewClient that will load any URL selected in our +WebView in the same WebView. You can see this in the <code>shouldOverrideUrlLoading()</code> +method, above—it is passed the current WebView and the URL, so all we do +is load the URL in the given view. Returning <var>true</var> says that we've handled the URL +ourselves and the event should not bubble-up.</p> + <p>If you try it again, new pages will now load in the HelloWebView Activity. However, you'll notice that +we can't navigate back. We need to handle the back button +on the device, so that it will return to the previous page, rather than exit the application.</p> + </li> + + <li>To handle the back button key press, add the following method inside the HelloWebView +Activity: +<pre> +@Override +public boolean onKeyDown(int keyCode, KeyEvent event) { + if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) { + webview.goBack(); + return true; + } + return super.onKeyDown(keyCode, event); +}</pre> + <p>The condition uses a {@link android.view.KeyEvent} to check + whether the key pressed is the BACK button and whether the + WebView is actually capable of navigating back (if it has a history). If both are + <em>not</em> true, then we send the event up the chain (and the Activity will close). + But if both <em>are</em> true, then we call <code>goBack()</code>, + which will navigate back one step in the history. We then return true to indicate + that we've handled the event.</p> +</li> +</ol> +<p>When you open the application, it should look like this:</p> +<img src="images/hello-webview.png" width="150px" /> + +<h3>Resource</h3> +<ul> +<li>{@link android.webkit.WebView}</li> +<li>{@link android.webkit.WebViewClient}</li> +<li>{@link android.view.KeyEvent}</li> +</ul> + +<p><a href="{@docRoot}guide/tutorials/views/hello-views-index.html">← Back to Hello Views</a></p> + + + + diff --git a/docs/html/guide/tutorials/views/images/android.png b/docs/html/guide/tutorials/views/images/android.png Binary files differnew file mode 100755 index 0000000..39a1ac7 --- /dev/null +++ b/docs/html/guide/tutorials/views/images/android.png diff --git a/docs/html/guide/tutorials/views/images/androidmarker.png b/docs/html/guide/tutorials/views/images/androidmarker.png Binary files differnew file mode 100755 index 0000000..8c43d46 --- /dev/null +++ b/docs/html/guide/tutorials/views/images/androidmarker.png diff --git a/docs/html/guide/tutorials/views/images/hello-autocomplete.png b/docs/html/guide/tutorials/views/images/hello-autocomplete.png Binary files differnew file mode 100755 index 0000000..e1fd80d --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-autocomplete.png diff --git a/docs/html/guide/tutorials/views/images/hello-datepicker.png b/docs/html/guide/tutorials/views/images/hello-datepicker.png Binary files differnew file mode 100755 index 0000000..2075066 --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-datepicker.png diff --git a/docs/html/guide/tutorials/views/images/hello-formstuff.png b/docs/html/guide/tutorials/views/images/hello-formstuff.png Binary files differnew file mode 100755 index 0000000..3b4bf54 --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-formstuff.png diff --git a/docs/html/guide/tutorials/views/images/hello-gallery.png b/docs/html/guide/tutorials/views/images/hello-gallery.png Binary files differnew file mode 100755 index 0000000..22d1eaf --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-gallery.png diff --git a/docs/html/guide/tutorials/views/images/hello-gridview.png b/docs/html/guide/tutorials/views/images/hello-gridview.png Binary files differnew file mode 100755 index 0000000..2def0df --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-gridview.png diff --git a/docs/html/guide/tutorials/views/images/hello-linearlayout.png b/docs/html/guide/tutorials/views/images/hello-linearlayout.png Binary files differnew file mode 100755 index 0000000..dfef819 --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-linearlayout.png diff --git a/docs/html/guide/tutorials/views/images/hello-listview.png b/docs/html/guide/tutorials/views/images/hello-listview.png Binary files differnew file mode 100755 index 0000000..a1cf7aa --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-listview.png diff --git a/docs/html/guide/tutorials/views/images/hello-mapview.png b/docs/html/guide/tutorials/views/images/hello-mapview.png Binary files differnew file mode 100755 index 0000000..0956760 --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-mapview.png diff --git a/docs/html/guide/tutorials/views/images/hello-relativelayout.png b/docs/html/guide/tutorials/views/images/hello-relativelayout.png Binary files differnew file mode 100755 index 0000000..ec4d9d4 --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-relativelayout.png diff --git a/docs/html/guide/tutorials/views/images/hello-spinner.png b/docs/html/guide/tutorials/views/images/hello-spinner.png Binary files differnew file mode 100755 index 0000000..42e2a91 --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-spinner.png diff --git a/docs/html/guide/tutorials/views/images/hello-tablelayout.png b/docs/html/guide/tutorials/views/images/hello-tablelayout.png Binary files differnew file mode 100755 index 0000000..3d80e7f --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-tablelayout.png diff --git a/docs/html/guide/tutorials/views/images/hello-timepicker.png b/docs/html/guide/tutorials/views/images/hello-timepicker.png Binary files differnew file mode 100755 index 0000000..bd5a1ee --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-timepicker.png diff --git a/docs/html/guide/tutorials/views/images/hello-webview.png b/docs/html/guide/tutorials/views/images/hello-webview.png Binary files differnew file mode 100755 index 0000000..283ce7d --- /dev/null +++ b/docs/html/guide/tutorials/views/images/hello-webview.png |