To create a text
entry widget that provides auto-complete suggestions, use the
For this Explanation we using two xml files:
AutoCompleteTextView
widget. Suggestions are received from a collection of strings
associated with the widget through an ArrayAdapter.For this Explanation we using two xml files:
list_item.xml:
<?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> main.xml: <?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:padding="5dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Country" /> <AutoCompleteTextView android:id="@+id/autocomplete_country" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp"/> </LinearLayout> Add below lines to your java class, static String[] COUNTRIES = new String[] { "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory","British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi","Cote d'Ivoire", "Cambodia", "Cameroon"}; AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country); ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, R.layout.list_item, COUNTRIES); textView.setAdapter(adapter);AutoCompleteTextViewwidget is captured from the layout withfindViewById(int). A newArrayAdapteris then initialized to bind thelist_item.xmllayoutto each list item in theCOUNTRIESstring array (defined in the next step).Finally,setAdapter()is called to associate theArrayAdapterwith theAutoCompleteTextViewwidget so that the string array will populate the list of suggestions. Here is the ScreenShot: