AutoCompleteTextView and MultiAutoCompleteTextView example in Android Android 20.10.2016

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 item 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(); 
    } 
});

Also you can handle the AutocompleteTextView field click event using setOnTouchListener() method. Place below lines of code in onCreate() method.

acPlanets.setOnTouchListener(new View.OnTouchListener(){
    @Override
    public boolean onTouch(View v, MotionEvent event){
        acPlanets.showDropDown();
        return false;
    }
});

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.

Also we can use SimpleCursorAdapter instead of ArrayAdapter. The following example code would typically be found in the onCreate() method of the Activity that contains the AutoCompleteTextView. It retrieves the AutoCompleteTextView from the Activity's layout, creates a SimpleCursorAdapter, configures that SimpleCursorAdapter to work with the AutoCompleteTextView, and then assigns the Adapter to the View.

final AutoCompleteTextView acSQL = (AutoCompleteTextView) findViewById(R.id.item_name_view);
SimpleCursorAdapter sqlAdapter = new SimpleCursorAdapter(this, R.layout.completion_item, sqlCursor, fromCol, toView);
sqlAdapter.setStringConversionColumn(sqlCursor.getColumnIndexOrThrow(dbAdapter.ITEM_NAME_COL));
sqlAdapter.setFilterQueryProvider(new FilterQueryProvider() {
    public Cursor runQuery(CharSequence constraint) {
        String name = null;
        if (constraint != null) {
            name = constraint.toString();
        }
        return db.suggestItemCompletions(name);
    }
});
acSQL.setAdapter(sqlAdapter);

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

AutoCompleteTextView example in Kotlin

Following is MainActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Initialize a new array with elements
        val colors = arrayOf(
                "Red","Green","Blue","Maroon","Magenta",
                "Gold","GreenYellow"
        )


        // Initialize a new array adapter object
        val adapter = ArrayAdapter<String>(
                this, // Context
                android.R.layout.simple_dropdown_item_1line, // Layout
                colors // Array
        )


        // Set the AutoCompleteTextView adapter
        auto_complete_text_view.setAdapter(adapter)


        // Auto complete threshold
        // The minimum number of characters to type to show the drop down
        auto_complete_text_view.threshold = 1


        // Set an item click listener for auto complete text view
        auto_complete_text_view.onItemClickListener = AdapterView.OnItemClickListener{
            parent,view,position,id->
            val selectedItem = parent.getItemAtPosition(position).toString()
            // Display the clicked item using toast
            Toast.makeText(applicationContext,"Selected : $selectedItem",Toast.LENGTH_SHORT).show()
        }


        // Set a dismiss listener for auto complete text view
        auto_complete_text_view.setOnDismissListener {
            Toast.makeText(applicationContext,"Suggestion closed.",Toast.LENGTH_SHORT).show()
        }


        // Set a click listener for root layout
        root_layout.setOnClickListener{
            val text = auto_complete_text_view.text
            Toast.makeText(applicationContext,"Inputted : $text",Toast.LENGTH_SHORT).show()
        }


        // Set a focus change listener for auto complete text view
        auto_complete_text_view.onFocusChange { v, hasFocus ->
            if(hasFocus) {
                // Display the suggestion dropdown on focus
                auto_complete_text_view.showDropDown()
            }
        }
   }
}

Following is layout for MainActivity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    >
    <AutoCompleteTextView
        android:id="@+id/auto_complete_text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>