From 5615ca1979caa79041bf16a2cae49f9cfadd7ee5 Mon Sep 17 00:00:00 2001 From: Scott Main Date: Tue, 15 Dec 2009 19:38:16 -0800 Subject: docs: a lot of revision and expansion of the hello view tutorials includes new screenshots for some tutorials and a new sample images zip file Bug:2338253 --- .../tutorials/views/hello-autocomplete.jd | 107 ++++-- .../resources/tutorials/views/hello-datepicker.jd | 144 ++++--- .../resources/tutorials/views/hello-formstuff.jd | 380 +++++++++++------- .../resources/tutorials/views/hello-gallery.jd | 116 ++++-- .../resources/tutorials/views/hello-gridview.jd | 119 ++++-- .../tutorials/views/hello-linearlayout.jd | 191 ++++----- .../resources/tutorials/views/hello-listview.jd | 120 +++++- .../resources/tutorials/views/hello-mapview.jd | 426 +++++++++++---------- .../tutorials/views/hello-relativelayout.jd | 52 ++- .../resources/tutorials/views/hello-spinner.jd | 121 ++++-- .../resources/tutorials/views/hello-tablelayout.jd | 30 +- .../resources/tutorials/views/hello-tabwidget.jd | 220 +++++++---- .../resources/tutorials/views/hello-timepicker.jd | 182 ++++----- .../resources/tutorials/views/hello-webview.jd | 175 +++++---- .../tutorials/views/images/android_focused.png | Bin 0 -> 2785 bytes .../tutorials/views/images/android_normal.png | Bin 0 -> 2056 bytes .../tutorials/views/images/android_pressed.png | Bin 0 -> 2337 bytes .../tutorials/views/images/hello-autocomplete.png | Bin 4601 -> 17719 bytes .../tutorials/views/images/hello-formstuff.png | Bin 4258 -> 23272 bytes .../tutorials/views/images/hello-listview.png | Bin 6926 -> 26359 bytes .../tutorials/views/images/hello-mapview.png | Bin 16922 -> 50499 bytes .../tutorials/views/images/hello-tabwidget.png | Bin 2117 -> 10393 bytes .../tutorials/views/images/hello-webview.png | Bin 5874 -> 16490 bytes .../tutorials/views/images/ic_tab_artists_grey.png | Bin 0 -> 791 bytes .../views/images/ic_tab_artists_white.png | Bin 0 -> 1127 bytes docs/html/resources/tutorials/views/index.jd | 127 +++--- 26 files changed, 1537 insertions(+), 973 deletions(-) create mode 100644 docs/html/resources/tutorials/views/images/android_focused.png create mode 100644 docs/html/resources/tutorials/views/images/android_normal.png create mode 100644 docs/html/resources/tutorials/views/images/android_pressed.png mode change 100755 => 100644 docs/html/resources/tutorials/views/images/hello-autocomplete.png mode change 100755 => 100644 docs/html/resources/tutorials/views/images/hello-formstuff.png mode change 100755 => 100644 docs/html/resources/tutorials/views/images/hello-listview.png mode change 100755 => 100644 docs/html/resources/tutorials/views/images/hello-mapview.png mode change 100755 => 100644 docs/html/resources/tutorials/views/images/hello-webview.png create mode 100644 docs/html/resources/tutorials/views/images/ic_tab_artists_grey.png create mode 100644 docs/html/resources/tutorials/views/images/ic_tab_artists_white.png (limited to 'docs/html/resources') diff --git a/docs/html/resources/tutorials/views/hello-autocomplete.jd b/docs/html/resources/tutorials/views/hello-autocomplete.jd index fba1ad8..e26683d 100644 --- a/docs/html/resources/tutorials/views/hello-autocomplete.jd +++ b/docs/html/resources/tutorials/views/hello-autocomplete.jd @@ -1,56 +1,82 @@ -page.title=Hello, AutoCompleteTextView +page.title=Auto Complete parent.title=Hello, Views parent.link=index.html @jd:body -

{@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.

+

To create a text entry widget that provides auto-complete suggestions, use +the {@link android.widget.AutoCompleteTextView} widget. Suggestions are received from a +collection of strings associated with the widget through an {@link +android.widget.ArrayAdapter}.

+ +

In this tutorial, you will create a {@link android.widget.AutoCompleteTextView} widget that +provides suggestions for a country name.

    -
  1. Start a new project/Activity called HelloAutoComplete.
  2. -
  3. Open the layout file. - Make it like so: +
  4. Start a new project named HelloAutoComplete.
  5. +
  6. Create an XML file named list_item.xml and save it inside the +res/layout/ folder. Edit the file to look like this: +
    +<?xml version="1.0" encoding="utf-8"?>
    +<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:layout_width="fill_parent"
    +    android:layout_height="fill_parent"
    +    android:padding="10dp"
    +    android:textSize="16sp"
    +    android:textColor="#000">
    +</TextView>
    +
    +

    This file defines a simple {@link android.widget.TextView} that will be used for each +item that appears in the list of suggestions.

    +
  7. +
  8. Open the res/layout/main.xml file and insert the following:
     <?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">
    -
    +    android:layout_height="wrap_content"
    +    android:padding="5dp">
         <TextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="Country" />
    -
    -    <AutoCompleteTextView android:id="@+id/edit"
    +    <AutoCompleteTextView android:id="@+id/autocomplete_country"
             android:layout_width="fill_parent"
    -        android:layout_height="wrap_content"/>
    -
    +        android:layout_height="wrap_content"
    +        android:layout_marginLeft="5dp"/>
     </LinearLayout>
     
    +

    The {@link android.widget.TextView} is a label that introduces the {@link +android.widget.AutoCompleteTextView} widget.

  9. -
  10. Open HelloAutoComplete.java and insert the following as the onCreate method: +
  11. Open HelloAutoComplete.java and insert the following code for the {@link +android.app.Activity#onCreate(Bundle) onCreate()} method:
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     
    -    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
    -    ArrayAdapter adapter = new ArrayAdapter(this,
    -            android.R.layout.simple_dropdown_item_1line, COUNTRIES);
    +    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
    +    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES);
         textView.setAdapter(adapter);
     }
     
    -

    Here, we create an AutoComplteteTextView from our layout. We then - create an {@link android.widget.ArrayAdapter} that binds a simple_dropdown_item_1line - layout item to each entry in the COUNTRIES array (which we'll add next). - The last part sets the ArrayAdapter to associate with our AutoCompleteTextView.

    + +

    After the content view is set to the main.xml layout, the {@link +android.widget.AutoCompleteTextView} widget is captured from the layout with {@link +android.app.Activity#findViewById(int)}. A new {@link +android.widget.ArrayAdapter} is then initialized to bind the list_item.xml layout +to each list item in the COUNTRIES string array (defined in the next step). +Finally, {@link android.widget.AutoCompleteTextView#setAdapter(T) setAdapter()} is called to +associate the {@link android.widget.ArrayAdapter} with the +{@link android.widget.AutoCompleteTextView} widget so that the string array will populate +the list of suggestions.

  12. -
  13. After the onCreate() method, add the String array: +
  14. Inside the HelloAutoComplete class, add the string array:
     static final String[] COUNTRIES = new String[] {
       "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
    @@ -96,19 +122,50 @@ static final String[] COUNTRIES = new String[] {
       "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
     };
     
    -

    This is the list of suggestions that will be offered as the user types into the - AutoCompleteTextView.

    +

    This is the list of suggestions that will be provided in a drop-down list when the user types into +the {@link android.widget.AutoCompleteTextView} widget.

  15. -
  16. Now run it.
  17. +
  18. Run the application.

As you type, you should see something like this:

+

More Information

+ +

Note that using a hard-coded string array is not a recommended design practice because your +application code should focus on behavior, not content. Application content such as strings +should be externalized from the code in order to make modifications to the content easier and +facilitate localization of the content. The hard-coded strings are used in this tutorial only to +make it simple and focus on the {@link android.widget.AutoCompleteTextView} widget. +Instead, your application should declare such string arrays in an XML file. This can be done +with a {@code <string-array<} resource in your project {@code res/values/strings.xml} file. +For example:

+
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string-array name="countries_array">
+        <item>Bahrain</item>
+        <item>Bangladesh</item>
+        <item>Barbados</item>
+        <item>Belarus</item>
+        <item>Belgium</item>
+        <item>Belize</item>
+        <item>Benin</item>
+    </string-array>
+</resources>
+
+

To use these resource strings for the {@link android.widget.ArrayAdapter}, replace the original +{@link android.widget.ArrayAdapter} constructor line with the following:

+
+String[] countries = getResources().getStringArray(R.array.countries_array);
+ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, countries);
+
+ +

References

diff --git a/docs/html/resources/tutorials/views/hello-datepicker.jd b/docs/html/resources/tutorials/views/hello-datepicker.jd index fcd43f3..c50d650 100644 --- a/docs/html/resources/tutorials/views/hello-datepicker.jd +++ b/docs/html/resources/tutorials/views/hello-datepicker.jd @@ -1,52 +1,57 @@ -page.title=Hello, DatePicker +page.title=Date Picker parent.title=Hello, Views parent.link=index.html @jd:body -

A {@link android.widget.DatePicker} is a widget that allows the user to select a month, day and year.

+

To provide a widget for selecting a date, use the {@link android.widget.DatePicker} +widget, which allows the user to select the month, day, and year, in a familiar interface.

+

In this tutorial, you'll create a {@link android.app.DatePickerDialog}, which presents the +date picker in a floating dialog box at the press of a button. When the date is set by +the user, a {@link android.widget.TextView} will update with the new date.

    -
  1. Start a new project/Activity called HelloDatePicker.
  2. -
  3. Open the layout file and make it like so: -
    +  
  4. Start a new project named HelloDatePicker.
  5. +
  6. Open the res/layout/main.xml file and insert the following: +
     <?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=""/>
    -
    +        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"/>
    -
    +        android:layout_width="wrap_content"
    +        android:layout_height="wrap_content"
    +        android:text="Change the date"/>
     </LinearLayout>
     
    -

    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.

    -
  7. - -
  8. Open HelloDatePicker.java. Insert the following to the HelloDatePicker class: +

    This creates a basic {@link android.widget.LinearLayout} with a {@link android.widget.TextView} + that will display the date and a {@link android.widget.Button} that will open the {@link + android.app.DatePickerDialog}.

    +
  9. + +
  10. Open HelloDatePicker.java and add the following members to the class:
         private TextView mDateDisplay;
         private Button mPickDate;
    -
         private int mYear;
         private int mMonth;
         private int mDay;
     
         static final int DATE_DIALOG_ID = 0;
    +
    +

    The first group of members define variables for the layout {@link android.view.View}s and the +date items. The DATE_DIALOG_ID is a static integer that uniquely identifies the {@link +android.app.Dialog} that will display the date picker.

    +
  11. - @Override +
  12. Now add the following code for the {@link android.app.Activity#onCreate(Bundle) onCreate()} +method: +
         protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
    @@ -68,43 +73,30 @@ parent.link=index.html
             mMonth = c.get(Calendar.MONTH);
             mDay = c.get(Calendar.DAY_OF_MONTH);
     
    -        // display the current date
    +        // display the current date (this method is below)
             updateDisplay();
         }
     
    -

    Tip: Press Ctrl(or Cmd) + Shift + O to import all needed packages.

    -

    We start by instantiating variables for our Views and date fields. - The DATE_DIALOG_ID is a static integer that uniquely identifies the Dialog. In the - onCreate() 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 showDialog() method will pop-up the date picker dialog - by calling the onCreateDialog() 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 - updateDisplay()—our own method (defined later) that will fill the TextView.

    -
  13. -
  14. After the onCreate() method, add the onCreateDialog() callback method -(which is called by showDialog()) -
    -@Override
    -protected Dialog onCreateDialog(int id) {
    -    switch (id) {
    -    case DATE_DIALOG_ID:
    -        return new DatePickerDialog(this,
    -                    mDateSetListener,
    -                    mYear, mMonth, mDay);
    -    }
    -    return null;
    -}
    -
    -

    This method is passed the identifier we gave showDialog() and initializes - the DatePicker to the date we retrieved from our Calendar instance.

    +

    First, the content is set to the main.xml layout. Then the {@link +android.widget.TextView} and {@link android.widget.Button} elements are captured from the layout +with {@link android.app.Activity#findViewById(int)}. A +new {@link android.view.View.OnClickListener} is created for the +{@link android.widget.Button}, so that when it is clicked, it +will call {@link android.app.Activity#showDialog(int)}, passing the unique integer ID for +the date picker dialog. Using {@link android.app.Activity#showDialog(int)} allows the {@link +android.app.Activity} to manage the life-cycle of the dialog and will call the {@link +android.app.Activity#onCreateDialog(int)} callback method to request the {@link android.app.Dialog} +that should be displayed (which you'll +define later). After the on-click listener is set, a new {@link java.util.Calendar} is created +and the current year, month and day are acquired. Finally, the private +updateDisplay() method is called in order to fill the {@link android.widget.TextView} +with the current date.

  15. -
  16. Following that, add the updateDisplay() method: +
  17. Add the updateDisplay() method:
    -    // updates the date we display in the TextView
    +    // updates the date in the TextView
         private void updateDisplay() {
             mDateDisplay.setText(
                 new StringBuilder()
    @@ -114,9 +106,13 @@ protected Dialog onCreateDialog(int id) {
                         .append(mYear).append(" "));
         }
     
    -

    This uses the member date values to write the date to our TextView.

    +

    This method uses the member date values declared for the class to write the date to the layout's +{@link android.widget.TextView}, {@code mDateDisplay}, which was also declared and initialized +above.

  18. -
  19. Finally, add a listener that will be called when the user sets a new date: + +
  20. Initialize a new {@link android.app.DatePickerDialog.OnDateSetListener} as a member of the +HelloDatePicker class:
         // the callback received when the user "sets" the date in the dialog
         private DatePickerDialog.OnDateSetListener mDateSetListener =
    @@ -131,19 +127,45 @@ protected Dialog onCreateDialog(int id) {
                     }
                 };
     
    -

    This OnDateSetListener 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 updateDisplay().

    +

    The {@link android.app.DatePickerDialog.OnDateSetListener} listens for when the user +has set the date (by clicking the "Set" button). At that time, the {@link +android.app.DatePickerDialog.OnDateSetListener#onDateSet(DatePicker,int,int,int) onDateSet()} +callback method is called, which is defined to update the {@code mYear}, {@code mMonth}, and +{@code mDay} member fields with the new date then call the private updateDisplay() +method to update the {@link android.widget.TextView}.

    +
  21. + +
  22. Now add the {@link android.app.Activity#onCreateDialog(int)} callback method to the {@code +HelloDatePicker} class: +
    +@Override
    +protected Dialog onCreateDialog(int id) {
    +    switch (id) {
    +    case DATE_DIALOG_ID:
    +        return new DatePickerDialog(this,
    +                    mDateSetListener,
    +                    mYear, mMonth, mDay);
    +    }
    +    return null;
    +}
    +
    +

    This is an {@link android.app.Activity} callback method that is passed the integer ID given to +{@link android.app.Activity#showDialog(int)} (which is called by the button's {@link +android.view.View.OnClickListener}). When the ID matches the switch case defined here, a {@link +android.app.DatePickerDialog} is instantiated with the {@link +android.app.DatePickerDialog.OnDateSetListener} created in the previous +step, along with the date variables to initialize the widget date.

  23. -
  24. Now run it.
  25. +
  26. Run the application.

When you press the "Change the date" button, you should see the following:

References

diff --git a/docs/html/resources/tutorials/views/hello-gallery.jd b/docs/html/resources/tutorials/views/hello-gallery.jd index 084f912..12d5a91 100644 --- a/docs/html/resources/tutorials/views/hello-gallery.jd +++ b/docs/html/resources/tutorials/views/hello-gallery.jd @@ -1,16 +1,21 @@ -page.title=Hello, Gallery +page.title=Gallery parent.title=Hello, Views parent.link=index.html @jd:body -

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.

+

{@link android.widget.Gallery} is a layout widget used to display items in a +horizontally scrolling list and positions the current selection at the center of the view.

+ +

In this tutorial, you'll create a gallery of photos and then display a toast message each time a +gallery item is selected.

    -
  1. Start a new project/Activity called HelloGallery.
  2. -
  3. Add some images to your res/drawable/ directory.
  4. -
  5. Open the layout file and make it like so: +
  6. Start a new project named HelloGallery.
  7. +
  8. Find some photos you'd like to use, or use these sample images. Save the images into the project's +res/drawable/ directory.
  9. +
  10. Open the res/layout/main.xml file and insert the following:
     <?xml version="1.0" encoding="utf-8"?>
     <Gallery xmlns:android="http://schemas.android.com/apk/res/android" 
    @@ -19,10 +24,10 @@ that locks the current selection at the center. When one is selected, we'll show
         android:layout_height="wrap_content"
     />
     
    -
  11. - + -
  12. Open the HelloGallery.java file. Insert the following for the onCreate() method: +
  13. Open the HelloGallery.java file and insert the following code for the +{@link android.app.Activity#onCreate(Bundle) onCreate()} method:
     @Override
     public void onCreate(Bundle savedInstanceState) {
    @@ -39,19 +44,46 @@ public void onCreate(Bundle savedInstanceState) {
         });
     }
     
    -

    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 onItemClick() 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 Toast.makeText().show(). +

    This starts by setting the {@code main.xml} layout as the content view and then capturing the +{@link android.widget.Gallery} from +the layout with {@link +android.app.Activity#findViewById(int)}. A custom {@link android.widget.BaseAdapter} called +ImageAdapter is +instantiated and applied to the {@link android.widget.Gallery} with {@link +android.widget.AdapterView#setAdapter(T) setAdapter()}. (The ImageAdapter class is +defined next.) +Then an anonymous {@link android.widget.AdapterView.OnItemClickListener} is instantiated. The +{@link android.widget.AdapterView.OnItemClickListener#onItemClick(AdapterView,View,int,long)} +callback method receives the {@link android.widget.AdapterView} where the click occurred, the +specific {@link android.view.View} that received the click, the +position of the {@link android.view.View} clicked (zero-based), and the row ID of the item clicked +(if applicable). In this example, all that's needed is the position of the click to show a {@link +android.widget.Toast} message that says the position of the item, using +{@link android.widget.Toast#makeText(Context,CharSequence,int)} and {@link +android.widget.Toast#show()} (in a real world scenario, this ID could be used to get the full sized +image for some other task).

  14. - -
  15. After the onCreate() method, add the ImageAdapter class: +
  16. Create a new XML file in the res/values/ directory named attrs.xml. +Insert the following: +
    +<?xml version="1.0" encoding="utf-8"?>
    +<resources>
    +    <declare-styleable name="HelloGallery">
    +        <attr name="android:galleryItemBackground" />
    +    </declare-styleable>
    +</resources>
    +
    +

    This is a custom styleable resource that can be applied to a layout. In this case, it will be +applied to the individual items placed into the {@link android.widget.Gallery} widget. The +<attr> element defines a specific attribute for the styleable, and in this case, it +refers to an existing platform attribute, {@link android.R.attr#galleryItemBackground}, which +defines a border styling for gallery items. In the next step, you'll +see how this attribute is referenced and then later applied to each item in the gallery.

    +
  17. + +
  18. Go back to the HelloGallery.java file. After the {@link + android.app.Activity#onCreate(Bundle)} method, define the custom ImageAdapter class:
     public class ImageAdapter extends BaseAdapter {
         int mGalleryItemBackground;
    @@ -100,26 +132,30 @@ public class ImageAdapter extends BaseAdapter {
     }
     

    First, there are a few member variables, including an array of IDs that reference -the images we placed in our drawable resources directory.

    -

    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 mGalleryItemBackground, it's important to recycle the -StyledAttribute for later re-use.

    -

    The next three methods are required for basic member queries. -But then we have the getView() 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.

    - -

    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.

    - -
  19. Now run it.
  20. +the images saved in the drawable resources directory ({@code res/drawable/}).

    +

    Next is the class constructor, where the {@link android.content.Context} for an {@code +ImageAdapter} instance is defined and the styleable +resource defined in the last step is acquired and saved to a local field. At the end of the +constructor, {@link android.content.res.TypedArray#recycle()} is called on the {@link +android.content.res.TypedArray} so it can be re-used by the system.

    +

    The methods {@link android.widget.Adapter#getCount()}, {@link +android.widget.Adapter#getItem(int)}, and {@link android.widget.Adapter#getItemId(int)} are methods +that must be implemented for simple queries on the {@link android.widget.Adapter}. +The {@link android.widget.Adapter#getView(int,View,ViewGroup) method does the +work to apply an image to an {@link android.widget.ImageView} that will be embedded in the +{@link android.widget.Gallery}. In this method, the member {@link android.content.Context} is used +to create a new {@link android.widget.ImageView}. The {@link android.widget.ImageView} is prepared +by applying an image from the local array of drawable resources, setting the {@link +android.widget.Gallery.LayoutParams} height and width for the image, setting the scale to fit the +{@link android.widget.ImageView} dimensions, and then finally setting the background to use the +styleable attribute acquired in the constructor.

    + +

    See {@link android.widget.ImageView.ScaleType} for other image scaling options.

    + + +
  21. Run the application.
+

You should see something like this:

@@ -129,7 +165,7 @@ exactly match the ImageView dimensions.

  • {@link android.widget.BaseAdapter}
  • {@link android.widget.Gallery}
  • {@link android.widget.ImageView}
  • -
  • {@link android.widget.Toast}
  • +
  • {@link android.widget.AdapterView.OnItemClickListener}
  • diff --git a/docs/html/resources/tutorials/views/hello-gridview.jd b/docs/html/resources/tutorials/views/hello-gridview.jd index ffb6c93..03bfc54 100644 --- a/docs/html/resources/tutorials/views/hello-gridview.jd +++ b/docs/html/resources/tutorials/views/hello-gridview.jd @@ -1,33 +1,44 @@ -page.title=Hello, GridView +page.title=Grid View parent.title=Hello, Views parent.link=index.html @jd:body -

    A {@link android.widget.GridView} displays items in a two-dimensional, scrolling grid. The items -are acquired from a {@link android.widget.ListAdapter}.

    +

    {@link android.widget.GridView} is a {@link android.view.ViewGroup} that displays items in a +two-dimensional, +scrollable grid. The grid items are automatically inserted to the layout using a {@link +android.widget.ListAdapter}.

    + +

    In this tutorial, you'll create a grid of image thumbnails. When an item is selected, a +toast message will display the position of the image.

      -
    1. Start a new project/Activity called HelloGridView.
    2. -
    3. Find some photos you'd like to use, or copy some from the SDK samples res/drawable/ - folder of your project.
    4. -
    5. Open the layout and make it like so: +
    6. Start a new project named HelloGridView.
    7. +
    8. Find some photos you'd like to use, or download these sample images. Save the image files +into the project's +res/drawable/ directory.
    9. +
    10. Open the res/layout/main.xml file and insert the following:
       <?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:columnWidth="90dp"
           android:numColumns="auto_fit"
           android:verticalSpacing="10dp"
           android:horizontalSpacing="10dp"
      -    android:columnWidth="90dp"
           android:stretchMode="columnWidth"
           android:gravity="center"
       />
       
      +

      This {@link android.widget.GridView} will fill the entire screen. The attributes are rather +self explanatory. For more information about valid attributes, see the {@link +android.widget.GridView} reference.

    11. -
    12. Open the HelloGridView Java file. Insert the following for the onCreate() method: +
    13. Open HelloGridView.java and insert the following code for the +{@link android.app.Activity#onCreate(Bundle) onCreate()} method:
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
      @@ -35,12 +46,33 @@ public void onCreate(Bundle savedInstanceState) {
       
           GridView gridview = (GridView) findViewById(R.id.gridview);
           gridview.setAdapter(new ImageAdapter(this));
      +
      +    gridview.setOnItemClickListener(new OnItemClickListener() {
      +        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
      +            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
      +        }
      +    });
       }
       
      -

      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.

      +

      After the {@code main.xml} layout is set for the content view, the +{@link android.widget.GridView} is captured from the layout with {@link +android.app.Activity#findViewById(int)}. The {@link +android.widget.GridView#setAdapter(T) setAdapter()} method then sets a custom adapter ({@code +ImageAdapter}) as the source for all items to be displayed in the grid. The {@code ImageAdapter} is +created in the next step.

      +

      To do something when an item in the grid is clicked, the {@link +android.widget.AdapterView#setOnItemClickListener(OnItemClickListener) setOnItemClickListener()} +method is passed a new {@link android.widget.AdapterView.OnItemClickListener}. This anonymous +instance defines the {@link +android.widget.AdapterView.OnItemClickListener#onItemClick(AdapterView,View,int,long) +onItemClick()} callback method to show a {@link android.widget.Toast} that displays the index +position (zero-based) of the selected item (in a real world scenario, the position could be used to +get the full sized +image for some other task).

      +
    14. -
    15. Create a new class (nested or otherwise), called ImageAdapter, which extends {@link android.widget.BaseAdapter}: +
    16. Create a new class called ImageAdapter that extends {@link +android.widget.BaseAdapter}:
       public class ImageAdapter extends BaseAdapter {
           private Context mContext;
      @@ -93,37 +125,58 @@ public class ImageAdapter extends BaseAdapter {
           };
       }
       
      -

      First we take care of some required methods inherited from BaseAdapter. - The constructor and getCount() are self-explanitory. Normally, getItem() - should return the actual object at the specified position in our Adapter, but for this Hello World, - we're not going to bother. Likewise, getItemId() should return the row id of - the item, but right now we don't care.

      -

      However, getView() 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 LayoutParams() 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 setScaleType(), 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 getView() we set the image resource and - return the ImageView.

      -

      All that's left is our array or drawable resources at the bottom.

      +

      First, this implements some required methods inherited from {@link +android.widget.BaseAdapter}. The constructor and {@link +android.widget.Adapter#getCount()} are self-explanatory. Normally, {@link +android.widget.Adapter#getItem(int)} should return the actual object at the specified position in +the adapter, but it's ignored for this example. Likewise, {@link +android.widget.Adapter#getItemId(int)} should return the row id of the item, but it's not +needed here.

      + +

      The first method necessary is {@link android.widget.Adapter#getView(int,View,ViewGroup) +getView()}. This method creates a new {@link android.view.View} for each image added to the {@code +ImageAdapter}. When this is called, a {@link android.view.View} is passed in, which is normally a +recycled object (at least after this has been called once), so there's a check to see if the +object is null. If it is null, an {@link android.widget.ImageView} is instantiated and +configured with desired properties for the image presentation:

      +
        +
      • {@link android.view.View#setLayoutParams(ViewGroup.LayoutParams)} sets +the height and width for the View—this ensures that, no matter the size of the drawable, each +image is resized and cropped to fit in these dimensions, as appropriate.
      • +
      • {@link android.widget.ImageView#setScaleType(ImageView.ScaleType)} declares that images should +be cropped toward the center (if necessary).
      • +
      • {@link android.widget.ImageView#setPadding(int,int,int,int)} defines the padding for all +sides. (Note that, if the images have different aspect-ratios, then less +padding will cause for more cropping of the image if it does not match +the dimensions given to the ImageView.)
      • +
      + +

      If the {@link android.view.View} passed to {@link +android.widget.Adapter#getView(int,View,ViewGroup) getView()} is not null, then the local +{@link android.widget.ImageView} is initialized with the recycled {@link android.view.View} +object.

      + +

      At the end of the {@link android.widget.Adapter#getView(int,View,ViewGroup) getView()} method, +the {@code +position} integer passed into the method is used to select an image from the {@code mThumbIds} +array, which is set as the image resource for the {@link android.widget.ImageView}.

      +

      All that's left is to define the {@code mThumbIds} array of drawable resources.

    17. -
    18. Run it.
    19. +
    20. Run the application.

    Your grid layout should look something like this:

    -

    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)}.

    +

    Try experimenting with the behaviors of the {@link android.widget.GridView} and {@link +android.widget.ImageView} elements by adjusting their properties. For example, instead of using +{@link android.view.View#setLayoutParams(ViewGroup.LayoutParams)}, try using +{@link android.widget.ImageView#setAdjustViewBounds(boolean)}.

    References

    diff --git a/docs/html/resources/tutorials/views/hello-linearlayout.jd b/docs/html/resources/tutorials/views/hello-linearlayout.jd index 0e8947c..8e072b1 100644 --- a/docs/html/resources/tutorials/views/hello-linearlayout.jd +++ b/docs/html/resources/tutorials/views/hello-linearlayout.jd @@ -1,16 +1,18 @@ -page.title=Hello, LinearLayout +page.title=Linear Layout parent.title=Hello, Views parent.link=index.html @jd:body -

    A {@link android.widget.LinearLayout} is a GroupView that will lay child View elements -vertically or horizontally.

    +

    {@link android.widget.LinearLayout} is a {@link android.view.ViewGroup} that displays child +{@link android.view.View} elements in a linear direction, either vertically or horizontally.

    +

    You should be careful about over-using the {@link android.widget.LinearLayout}. If you begin +nesting multiple {@link android.widget.LinearLayout}s, you may want to consider using a {@link +android.widget.RelativeLayout} instead.

      -
    1. Start a new project/Activity called HelloLinearLayout.
    2. -
    3. Open the layout file. - Make it like so: +
    4. Start a new project named HelloLinearLayout.
    5. +
    6. Open the res/layout/main.xml file and insert the following:
       <?xml version="1.0" encoding="utf-8"?>
       <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      @@ -18,113 +20,114 @@ vertically or horizontally.

      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"> + <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> - <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 + 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>
      -

      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.

      + +

      Carefully inspect this XML. There is a root {@link android.widget.LinearLayout} that defines +its orientation to be vertical—all child {@link android.view.View}s (of which it has two) will +be stacked vertically. The first child is +another {@link android.widget.LinearLayout} that uses a horizontal orientation and the second child +is a {@link android.widget.LinearLayout} that uses a vertical orientation. Each of these nested +{@link android.widget.LinearLayout}s contain several {@link android.widget.TextView} elements, which +are oriented with each other in the manner defined by their parent {@link +android.widget.LinearLayout}.

    7. -
    8. Now open the HelloLinearLayout Activity and be sure it loads this layout in the onCreate() method:

      +
    9. Now open HelloLinearLayout.java and be sure it loads the +res/layout/main.xml layout in the +{@link android.app.Activity#onCreate(Bundle) onCreate()} method:

       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.main);
       }
       
      -

      R.layout.main refers to the main.xml layout file.

      +

      The {@link android.app.Activity#setContentView(int)} method loads the +layout file for the {@link android.app.Activity}, specified by the resource +ID — R.layout.main refers to the res/layout/main.xml layout +file.

    10. -
    11. Run it.
    12. +
    13. Run the application.

    You should see the following:

    -

    Notice how the various XML attributes define the View's behavior. -Pay attention to the effect of the layout_weight. Try - experimenting with different values to see how the screen real estate is - distributed based on the weight of each element.

    +

    Notice how the XML attributes define each View's behavior. Try +experimenting with different values for android:layout_weight to see how the screen +real estate is distributed based on the weight of each element. See the Common Layout Objects +document for more about how {@link android.widget.LinearLayout} handles the +android:layout_weight attribute.

    References

    diff --git a/docs/html/resources/tutorials/views/hello-listview.jd b/docs/html/resources/tutorials/views/hello-listview.jd index d90005b..194258e 100644 --- a/docs/html/resources/tutorials/views/hello-listview.jd +++ b/docs/html/resources/tutorials/views/hello-listview.jd @@ -1,36 +1,88 @@ -page.title=Hello, ListView +page.title=List View parent.title=Hello, Views parent.link=index.html @jd:body -

    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}.

    +

    {@link android.widget.ListView} is a {@link android.view.ViewGroup} that creates a list of +scrollable items. The list items are automatically inserted to the list using a {@link +android.widget.ListAdapter}.

    +

    In this tutorial, you'll create a scrollable list of country names that are read from a string array. +When a list item is selected, a toast message will display the position of the item in the list.

      -
    1. Start a new project/ListActivity called HelloListView.
    2. -
    3. Open the HelloListView Java file. Make the class extend ListActivity (instead of Activity). +
    4. Start a new project named HelloListView.
    5. +
    6. Create an XML file named list_item.xml and save it inside the +res/layout/ folder. Insert the following: +
      +<?xml version="1.0" encoding="utf-8"?>
      +<TextView xmlns:android="http://schemas.android.com/apk/res/android"
      +    android:layout_width="fill_parent"
      +    android:layout_height="fill_parent"
      +    android:padding="10dp"
      +    android:textSize="16sp" >
      +</TextView>
      +
      +

      This file defines the layout for each item that will be placed in the {@link +android.widget.ListView}.

      +
    7. + +
    8. Open the HelloListView.java and make the class extend {@link +android.app.ListActivity} (instead of {@link android.app.Activity}):
      public class HelloListView extends ListActivity {
    9. -
    10. Insert the following for the onCreate() method: +
    11. Insert the following code for the {@link android.app.Activity#onCreate(Bundle) onCreate()} +method:
       @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);
      +
      +  setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
      +
      +  ListView lv = getListView();
      +  lv.setTextFilterEnabled(true);
      +
      +  lv.setOnItemClickListener(new OnItemClickListener() {
      +    public void onItemClick(AdapterView<?> parent, View view,
      +        int position, long id) {
      +      // When clicked, show a toast with the TextView text
      +      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
      +          Toast.LENGTH_SHORT).show();
      +    }
      +  });
       }
       
      -

      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 setListAdapter() (which automatically - adds a ListView to the ListActivity), and provide it with an ArrayAdapter that binds a - simple_list_item_1 layout item to each entry in the COUNTRIES - 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.

      -
    12. -
    13. Following the onCreate() method, add the String array: +

      Notice that this does not load a layout file for the Activity (which you usually do with {@link +android.app.Activity#setContentView(int)}). Instead, {@link +android.app.ListActivity#setListAdapter(ListAdapter)} automatically +adds a {@link android.widget.ListView} to fill the entire screen of the {@link +android.app.ListActivity}. This method takes an {@link android.widget.ArrayAdapter}, which +manages the array of list items that will be placed into the {@link android.widget.ListView}. The +{@link android.widget.ArrayAdapter} constructor takes the application {@link +android.content.Context}, the +layout description for each list item (created in +the previous step), and a {@link java.util.List} of objects to insert in the {@link +android.widget.ListView} (defined next).

      + +

      The {@link android.widget.ListView#setTextFilterEnabled(boolean)} method turns on text filtering +for the {@link android.widget.ListView}, so that when the user begins typing, the list will be +filtered.

      + +

      The {@link android.widget.ListView#setOnItemClickListener(OnItemClickListener)} method defines +the on-click listener for each item. When an item in the {@link android.widget.ListView} is clicked, +the {@link android.widget.AdapterView.OnItemClickListener#onItemClick(AdapterView,View,int,long) +onItemClick()} method is called and a {@link android.widget.Toast} message is displayed, using the +text from the clicked item.

      + +

      Tip: You can use list item designs provided by the platform +instead of defining your own layout file for the {@link android.widget.ListAdapter}. For example, +try using android.R.layout.simple_list_item_1 instead of +R.layout.list_item.

      +
    14. + +
    15. After the {@link android.app.Activity#onCreate(Bundle) onCreate()} method, add the string +array:
         static final String[] COUNTRIES = new String[] {
           "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
      @@ -76,12 +128,40 @@ public void onCreate(Bundle savedInstanceState) {
           "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
         };
       
      +

      This is the array of strings that will be placed into the {@link android.widget.ListView}.

    16. -
    17. Run it.
    18. +
    19. Run the application.
    -

    You can scroll the list, or type to filter it. You should see something like this:

    +

    You can scroll the list, or type to filter it, then click an item to see a message. You +should see something like this:

    +

    Note that using a hard-coded string array is not the best design practice. One is +used in this tutorial for simplicity, in order to demonstrate the {@link +android.widget.ListView} widget. The better practice is to reference a string array +defined by an external resource, such as with a {@code <string-array>} +resource in your project {@code res/values/strings.xml} file. For example:

    +
    +<?xml version="1.0" encoding="utf-8"?>
    +<resources>
    +    <string-array name="countries_array">
    +        <item>Bahrain</item>
    +        <item>Bangladesh</item>
    +        <item>Barbados</item>
    +        <item>Belarus</item>
    +        <item>Belgium</item>
    +        <item>Belize</item>
    +        <item>Benin</item>
    +    </string-array>
    +</resources>
    +
    +

    To use these resource strings for the {@link android.widget.ArrayAdapter}, replace the original +{@link android.app.ListActivity#setListAdapter(ListAdapter)} line with the following:

    +
    +String[] countries = getResources().getStringArray(R.array.countries_array);
    +setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, countries));
    +
    +

    References