Thursday, March 15, 2012

AutoCompleteTextView Tutorial


here is the layout xml file:
<AutoCompleteTextView
                        android:id="@+id/AndroidBooks"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content" >
                    </AutoCompleteTextView>
Nothing special. It just consists of one element.
Now in the main activity, I create an array of android books:
String[] androidBooks =
           {
           "Hello, Android - Ed Burnette",
           "Professional Android 2 App Dev - Reto Meier",
           "Unlocking Android - Frank Ableson",
           "Android App Development - Blake Meike",
           "Pro Android 2 - Dave MacLean",
           "Beginning Android 2 - Mark Murphy",
           "Android Programming Tutorials - Mark Murphy",
           "Android Wireless App Development - Lauren Darcey",
           "Pro Android Games - Vladimir Silva",
           };
Then in the onCreate(..) method, I create an ArrayAdapter that I can pass to thisAutoCompleteTextView as the data Source.

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,androidBooks);


Then, I get a handle to the AutocompleteTextView, and set the arrayAdapter to it along with the Threshold. The Threshold defines the number of charaters a user should type before the suggestions start showing up.

AutoCompleteTextView acTextView = (AutoCompleteTextView)findViewById(R.id.acTVCountry);
           acTextView.setThreshold(3);
           acTextView.setAdapter(adapter);
That is it. Now execute and see it work. 

This is the way it would look:


1 comment:

Unknown said...

I really like it. you have provided very good information