How to use AutoCompleteTextView in Android?
AutoCompleteTextView is 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. The list of suggestions is obtained from a data adapter, usually an array adapter.

Let us create a simple AutoCompleteTextView to enter a countries and supported by a list of countries for auto completion.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/autoCompleteTextView"
android:hint="Enter Country"/>
</LinearLayout>
Some of the other XML attributes that you can define:
| XML attributes | |
|---|---|
| android:completionHint | Defines the hint displayed in the drop down menu. |
| android:completionHintView | Defines the hint view displayed in the drop down menu. |
| android:completionThreshold | Defines the number of characters that the user must type before completion suggestions are displayed in a drop down menu. |
In Java, create an array of the countries that you want to allow auto complete for. Then, we create an ArrayAdapter of type String initialised by this array. An ArrayAdapter takes in 3 parameters: Context (Main Activity), layout resource id and the array (in this case the String array). For the layout, we use one of the default android provided simple dropdown layouts (android.R.layout.simple_dropdown_item_1line)
We then find the AutoCompleteTextView by id and set this ArrayAdapter to it.
Here’s the final java code:
public class MainActivity extends AppCompatActivity {
private String[] countries =
{"India", "USA", "Russia", "China", "Japan", "Indonesia"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the view
AutoCompleteTextView autoCompleteTextView =
(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
// Create an array adapter initialised with the countries array
ArrayAdapter adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, countries);
// Set the adapter to the AutoCompleteTextView
autoCompleteTextView.setAdapter(adapter);
}
}