AutoCompleteTextView and MultiAutoCompleteTextView example in Android

AutoCompleteTextView

A AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of completion suggestions automatically while the user is typing. The list of suggestions is displayed in drop down menu. The user can choose an item from there to replace the content of edit box with.

Following are the important attributes related to AutoCompleteTextView control.

  • android:completionHint. This defines the hint displayed in the drop down menu.
  • android:completionHintView. This defines the hint view displayed in the drop down menu.
  • android:completionThreshold. This property will define the number of characters that the user must type before completion suggestions are displayed in a drop-down menu.
  • android:dropDownAnchor. This is the View to anchor the auto-complete dropdown to.
  • android:popupBackground. This sets the background.

Add the following snippet to activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <AutoCompleteTextView
        android:id="@+id/planets"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        android:ems="15"
        android:completionHint="Select planet"
        android:hint="Planets">

        <requestFocus />
    </AutoCompleteTextView>

    <Button
        android:id="@+id/btnPlanet"
        android:layout_width="wrap_content"
        android:text="Show"
        android:layout_height="wrap_content"
        android:onClick="showSelected"
        android:layout_below="@+id/planets"
        />
</RelativeLayout>

Let's create array resource.

AutoCompleteTextView acPlanets;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final String planets[] = {"Mercury", "Venus", "Earth", "Mars"};

    acPlanets = (AutoCompleteTextView) findViewById(R.id.planets);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                    android.R.layout.simple_dropdown_item_1line, planets);
    acPlanets.setThreshold(2); //will start working from second character
    acPlanets.setAdapter(adapter);
}

public void showSelected(View v) {
    String planet = acPlanets.getText().toString();
    Toast.makeText(MainActivity.this, planet, Toast.LENGTH_SHORT).show();        
}

Accessing AutoCompleteTextView string data from selection is very easy because there are already a pre define function getText() available for retrieve entered value.

You can handle the AutocompleteTextView click event using setOnItemClickListener() method. Place below lines of code in onCreate() method.

acPlanets.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        String planet = parent.getItemAtPosition(position).toString(); 
        Toast toast = Toast.makeText(getApplicationContext(), planet, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0); 
        toast.show(); 
    } 
});

We can also set error if something gone wrong

acPlanets.setError("Invalid planet");

Android provides several text decorating attributes like Typeface, font family, text style, text size, text color, text shadow etc. that can be applied to AutoCompleteTextView.

You can define custom adapter, as described here.

MultiAutoCompleteTextView

MultiAutoCompleteTextView is same as AutoCompleteTextView but first can hold multiple string words value at single time. These all values are separated by comma (,).

Android AutoCompleteTextView is the subclass of EditText class. The MultiAutoCompleteTextView is the subclass of AutoCompleteTextView class.

Add the following snippet to activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <MultiAutoCompleteTextView
        android:id="@+id/planets"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:textSize="15dp"
        android:textColor="#FF0000"
        android:hint="Planets">
        <requestFocus />
    </MultiAutoCompleteTextView>

    <Button
        android:id="@+id/btnPlanet"
        android:layout_width="wrap_content"
        android:text="Show"
        android:layout_height="wrap_content"
        android:onClick="showSelected"
        android:layout_below="@+id/planets"
        />
</RelativeLayout>

Add the following code to MainActivity.

MultiAutoCompleteTextView acPlanets;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final String planets[] = {"Mercury", "Venus", "Earth", "Mars"};

    acPlanets = (MultiAutoCompleteTextView) findViewById(R.id.planets);
    acPlanets.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                    android.R.layout.simple_dropdown_item_1line, planets);
    acPlanets.setThreshold(1); //will start working from second character
    acPlanets.setAdapter(adapter);
}

public void showSelected(View v) {
    String planet = acPlanets.getText().toString();
    Toast.makeText(MainActivity.this, planet, Toast.LENGTH_SHORT).show();        
    String planets[] = planet.split(",");
    Log.d(TAG, planets[0]);
}

To customize suggestion box, I created a new layout as given below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:orientation="vertical">

   <TextView
       android:id="@+id/tvHintCompletion"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:padding="10dp"
       android:textColor="@color/colorPrimaryDark"
       android:textSize="16sp"
       android:textStyle="bold"/>

   <View
       android:layout_width="match_parent"
       android:layout_height="2dp"
       android:background="@color/colorAccent" />
</LinearLayout>

When I created adapter to handle MultiAutoCompleteTextView data, I just specified the layout and TextView which I want for suggestion box as follows:

adapter = new ArrayAdapter<String>(this, R.layout.hint_completion_layout, R.id.tvHintCompletion, planets);

Result

android_multiautocomplete.png
comments powered by Disqus