AutoCompleteTextView View
--see (Books/Android/Source Code/BasicViews3)
AutoCompleteTextView is like EditText but, addes the feature of autocompletion (adding a list of completion suggestions automatically while user types)
- Create instance of AutoCompleteTextView:
- in below example the instance created using XML declaration and then grab handle to it in code called textView
-
AutoCompleteTextView textView = (AutoCompleteTextView) findViewByID(R.id.txtCountries); //id parameter of xml is R.id.txtCountries
- in below example the instance created using XML declaration and then grab handle to it in code called textView
-
Create ArrayAdapter for Auto Completion: create an instance of ArrayAdapter using a String Array containing some Strings (in this example they are hardcoded but, you could read from file, database)
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simpe_dropdown_items_1line, presidents);
- Set the adapter for teh AutoCompleteTextView to the ArrayAdapter of string
-
myAutoCompleteTextView.setAdapter(adapter);
-
- EXAMPLE
- Note: setup so will not do autocomplete until user types 3 characters.
main.xml ( activities defined GUI in xml) <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Name of President" /> <AutoCompleteTextView android:id="@+id/txtCountries" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> |
BasicViews3Activity.java package net.learn2develop.BasicViews3; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; public class BasicViews3Activity extends Activity {
String[] presidents = { "Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson",
"Richard Nixon", "Gerald Ford", "Jimmy Carter", "Ronald Reagan", "George H. W. Bush",
"Bill Clinton", "George W. Bush", "Barack Obama" };
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //setup ArrayAdapter AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.txtCountries);
//user must type in 3 characters before autocomplete operation can start |