Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit f1c2f57f authored by The Android Automerger's avatar The Android Automerger
Browse files

Merge branch 'eclair' into eclair-release

parents 197744eb 8c166512
Loading
Loading
Loading
Loading
+82 −25
Original line number Diff line number Diff line
page.title=Hello, AutoCompleteTextView
page.title=Auto Complete
parent.title=Hello, Views
parent.link=index.html
@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>
<p>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}.</p>

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


<ol>
  <li>Start a new project/Activity called HelloAutoComplete.</li>
  <li>Open the layout file.
    Make it like so:
  <li>Start a new project named <em>HelloAutoComplete</em>.</li>
  <li>Create an XML file named <code>list_item.xml</code> and save it inside the
<code>res/layout/</code> folder. Edit the file to look like this:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;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">
&lt;/TextView>
</pre>
  <p>This file defines a simple {@link android.widget.TextView} that will be used for each
item that appears in the list of suggestions.</p>
  </li>
  <li>Open the <code>res/layout/main.xml</code> file and insert the following:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;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">
    &lt;TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Country" />

    &lt;AutoCompleteTextView android:id="@+id/edit"
    &lt;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"/>
&lt;/LinearLayout>
</pre>
  <p>The {@link android.widget.TextView} is a label that introduces the {@link
android.widget.AutoCompleteTextView} widget.
</li>

<li>Open HelloAutoComplete.java and insert the following as the <code>onCreate</code> method:
<li>Open <code>HelloAutoComplete.java</code> and insert the following code for the {@link
android.app.Activity#onCreate(Bundle) onCreate()} method:
<pre>
&#64;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, COUNTRIES);
    AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
    ArrayAdapter&lt;String> adapter = new ArrayAdapter&lt;String>(this, R.layout.list_item, COUNTRIES);
    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>

<p>After the content view is set to the <code>main.xml</code> 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 <code>list_item.xml</code> layout
to each list item in the <code>COUNTRIES</code> 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.</p>
</li>

<li>After the <code>onCreate()</code> method, add the String array:
<li>Inside the <code>HelloAutoComplete</code> class, add the string array:
<pre>
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"
};
</pre>
	<p>This is the list of suggestions that will be offered as the user types into the 
	AutoCompleteTextView.</p>
<p>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.</p>
</li>

<li>Now run it.</li>
<li>Run the application.</li>
</ol>
<p>As you type, you should see something like this:</p>
<img src="images/hello-autocomplete.png" width="150px" />


<h2>More Information</h2>

<p>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 &lt;string-array&lt;} resource in your project {@code res/values/strings.xml} file.
For example:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
    &lt;string-array name="countries_array">
        &lt;item>Bahrain&lt;/item>
        &lt;item>Bangladesh&lt;/item>
        &lt;item>Barbados&lt;/item>
        &lt;item>Belarus&lt;/item>
        &lt;item>Belgium&lt;/item>
        &lt;item>Belize&lt;/item>
        &lt;item>Benin&lt;/item>
    &lt;/string-array>
&lt;/resources>
</pre>
<p>To use these resource strings for the {@link android.widget.ArrayAdapter}, replace the original
{@link android.widget.ArrayAdapter} constructor line with the following:</p>
<pre>
String[] countries = getResources().getStringArray(R.array.countries_array);
ArrayAdapter&lt;String> adapter = new ArrayAdapter&lt;String>(this, R.layout.list_item, countries);
</pre>


<h3>References</h3>
<ul>
	<li>{@link android.R.layout}</li>
	<li>{@link android.widget.ArrayAdapter}</li>
	<li>{@link android.widget.AutoCompleteTextView}</li>
</ul>
+83 −61
Original line number Diff line number Diff line
page.title=Hello, DatePicker
page.title=Date Picker
parent.title=Hello, Views
parent.link=index.html
@jd:body

<p>A {@link android.widget.DatePicker} is a widget that allows the user to select a month, day and year.</p>
<p>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.</p>

<p>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.</p>

<ol>
  <li>Start a new project/Activity called HelloDatePicker.</li>
  <li>Open the layout file and make it like so:
  <li>Start a new project named <em>HelloDatePicker</em>.</li>
  <li>Open the <code>res/layout/main.xml</code> file and insert the following:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    &lt;TextView android:id="@+id/dateDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>

    &lt;Button android:id="@+id/pickDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change the date"/>

&lt;/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>
  <p>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}.</p>
  </li>

  <li>Open HelloDatePicker.java. Insert the following to the HelloDatePicker class:
  <li>Open <code>HelloDatePicker.java</code> and add the following members to the class:
<pre>
    private TextView mDateDisplay;
    private Button mPickDate;

    private int mYear;
    private int mMonth;
    private int mDay;

    static final int DATE_DIALOG_ID = 0;
</pre>
  <p>The first group of members define variables for the layout {@link android.view.View}s and the
date items. The <code>DATE_DIALOG_ID</code> is a static integer that uniquely identifies the {@link
android.app.Dialog} that will display the date picker.</p>
  </li>

    &#64;Override
  <li>Now add the following code for the {@link android.app.Activity#onCreate(Bundle) onCreate()}
method:
<pre>
    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();
    }
</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>&mdash;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>
&#64;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>
<p>First, the content is set to the <code>main.xml</code> 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
<code>updateDisplay()</code> method is called in order to fill the {@link android.widget.TextView}
with the current date.</p>
</li>

<li>Following that, add the <code>updateDisplay()</code> method:
<li>Add the <code>updateDisplay()</code> method:
<pre>
    // 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(" "));
    }
</pre>
<p>This uses the member date values to write the date to our TextView.</p>
<p>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.</p>
</li>
<li>Finally, add a listener that will be called when the user sets a new date:

<li>Initialize a new {@link android.app.DatePickerDialog.OnDateSetListener} as a member of the
<code>HelloDatePicker</code> class:
<pre>
    // 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) {
                }
            };
</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>
<p>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 <code>updateDisplay()</code>
method to update the {@link android.widget.TextView}.</p>
</li>

<li>Now add the {@link android.app.Activity#onCreateDialog(int)} callback method to the {@code
HelloDatePicker} class:
<pre>
&#64;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 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.</p>
</li>

<li>Now run it.</li>
<li>Run the application.</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.app.DatePickerDialog}</li>
<li>{@link android.app.DatePickerDialog.OnDateSetListener}</li>
<li>{@link android.widget.Button}</li>
<li>{@link android.widget.TextView}</li>
<li>{@link java.util.Calendar}</li>
+251 −129

File changed.

Preview size limit exceeded, changes collapsed.

+76 −40
Original line number Diff line number Diff line
page.title=Hello, Gallery
page.title=Gallery
parent.title=Hello, Views
parent.link=index.html
@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>
<p>{@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.</p>

<p>In this tutorial, you'll create a gallery of photos and then display a toast message each time a
gallery item is selected.</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:
  <li>Start a new project named <em>HelloGallery</em>.</li>
  <li>Find some photos you'd like to use, or use these <a
href="{@docRoot}shareables/sample_images.zip">sample images</a>. Save the images into the project's
<code>res/drawable/</code> directory.</li>
  <li>Open the <code>res/layout/main.xml</code> file and insert the following:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;Gallery xmlns:android="http://schemas.android.com/apk/res/android" 
@@ -21,8 +26,8 @@ that locks the current selection at the center. When one is selected, we'll show
</pre>
  </li>


<li>Open the HelloGallery.java file. Insert the following for the <code>onCreate()</code> method:
<li>Open the <code>HelloGallery.java</code> file and insert the following code for the
{@link android.app.Activity#onCreate(Bundle) onCreate()} method:
<pre>
&#64;Override
public void onCreate(Bundle savedInstanceState) {
@@ -39,19 +44,46 @@ public void onCreate(Bundle savedInstanceState) {
    });
}
</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&mdash;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>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
<code>ImageAdapter</code> is
instantiated and applied to the {@link android.widget.Gallery} with {@link
android.widget.AdapterView#setAdapter(T) setAdapter()}. (The <code>ImageAdapter</code> 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).
</p>
</li>
  <li>Create a new XML file in the <code>res/values/</code> directory named <code>attrs.xml</code>.
Insert the following:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
    &lt;declare-styleable name="HelloGallery">
        &lt;attr name="android:galleryItemBackground" />
    &lt;/declare-styleable>
&lt;/resources>
</pre>
  <p>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
<code>&lt;attr></code> 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.</p>
  </li>

<li>After the <code>onCreate()</code> method, add the <code>ImageAdapter</code> class:
  <li>Go back to the <code>HelloGallery.java</code> file. After the {@link
  android.app.Activity#onCreate(Bundle)} method, define the custom <code>ImageAdapter</code> class:
<pre>
public class ImageAdapter extends BaseAdapter {
    int mGalleryItemBackground;
@@ -100,26 +132,30 @@ public class ImageAdapter extends BaseAdapter {
}
</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>
the images saved in the drawable resources directory ({@code res/drawable/}).</p>
<p>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.</p>
<p>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.</p>

<p>See {@link android.widget.ImageView.ScaleType} for other image scaling options.</p>
</li>

<li>Run the application.</li>
</ol>

<p>You should see something like this:</p>
<img src="images/hello-gallery.png" width="150px" />

@@ -129,7 +165,7 @@ exactly match the ImageView dimensions.</p>
	<li>{@link android.widget.BaseAdapter}</li>
	<li>{@link android.widget.Gallery}</li>
	<li>{@link android.widget.ImageView}</li>
	<li>{@link android.widget.Toast}</li>
  <li>{@link android.widget.AdapterView.OnItemClickListener}</li>
</ul>

+86 −33

File changed.

Preview size limit exceeded, changes collapsed.

Loading