Android AutoCompleteTextView Example

     
AutoCompleteTextView
AutoCompleteTextView
AutoCompleteTextView is an editable text view that automatically shows completion suggestions while the user is typing. The suggestion list will appear in a drop down menu, allowing the user to choose one of the options and place it in the text box. This useful feature can make your application a lot more user friendly and easy to use. 





1.Adding AutoCompleteTextView to a layout file

          Our first step is to add an AutoCompleteTextView element to the application layout file. To do that go to the res/layout directory and add the following code to the xml layout file:


           As you can see our AutoCompleteTextView element appears on lines 17-20, where we are giving it an id and defining its width and height. I have also added two TextView elements, one of them is used to let a user know what he or she is expected to type in to the edit text box (feel free to get rid of it if you don't need it). I will use the second TextView to show you how you can extract and use users selection.

2. Modifying application activity 

          
            Now we need to initialize our AutoCompleteTextView element in the activity file and fill it with the suggestion that we want  to appear. Go to the src/packagename directory and paste the following code to the MainActivity.java file:


Code Explanation:

22-24 - a string array is created and filled with the values that later will be used as suggestions in our AutoCompleteTextView element;

31 - initialization of the AutoCompleteTextView;

33setOnItemClickListener public method is used to set a listener that will be notified when an item in the drop down list is clicked by a user;

39 - we set the value of the TextView to the one selected by a user;

44 - 49 in the loadData() method we use a data adapter to obtain the list of suggestions from our String array;  setThreshold public method id used to specify the minimum amount of characters that user has to type before the drop down list of suggestions is shown.

Source Code



References:
http://developer.android.com/reference/android/widget/AutoCompleteTextView.html
http://developer.android.com/reference/android/widget/ArrayAdapter.html