Friday, June 17, 2011

How to use a AutoCompleteTextView

AutoCompleteTextView an editable text view that shows completion suggestions automatically while the user is typing. The list of suggestions is displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with (from Android documentation).


Here is an example:


public class MyTestClass extends Activity
{
    AutoCompleteTextView myACTextView;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final String[] s= 
           getResources().
           getStringArray(R.array.myArrayStringData);
        myACTextView= (AutoCompleteTextView) 
                  findViewById(R.id.autoCompleteTextView);
        ArrayAdapter<String> myAdapter = 
                  new ArrayAdapter<String>(this,
                  android.R.layout.simple_dropdown_item_1line, s);
        myACTextView.setAdapter(myAdapter);

      ....your other code here ............

   }

}

================================================================
Provide the content of myArrayStringData in your res/values/strings.xml file as follows:


<?xml version="1.0" encoding="utf-8"?>
<resources>
   
    <string-array name="myArrayStringData">
       <item>ABC</item>
       <item>DEF</item>
       <item>GHI</item>
       <item>JKH</item>
     </string-array>
   
     <string name="myOtherString">Hello There!</string>
     
</resources>


Note: Alternatively, this array can be defined right in the Java code as: final String[] s= new String[] { "ABC", "DEF", "GHI", "JKL" };
==================================================================
Inside your main.xml, AutoCompleteTextView will look something like this. Note that,  per documentation, android:completionThreshold defines the number of characters that the user must type before completion suggestions are displayed in a drop down menu.


AutoCompleteTextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/autoCompleteTextView"
        android:completionThreshold="1"
        >
</AutoCompleteTextView>


No comments:

Post a Comment

Please do not hesitate to leave your comments.