Recipe 2.6 Using AutoCompleteTextView

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
AutoComplete.zip

While you can use an EditText view for entering text, it is sometimes useful to provide users with suggestions to automatically complete what they are typing. For example, if a user is typing a search string into an EditText, you can offer possible suggestions to complete the search string while the user is typing. In this case, you can use the AutoCompleteTextView to do so. This recipe shows you how.

Solution

The AutoCompleteTextView is an editable text view that shows completion suggestions while the user is typing. The suggestions are displayed as a drop-down menu that contains content that is supplied by you.

Assume you have the following code snippet in the activity_main.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Name of President" />

    <AutoCompleteTextView
        android:id="@+id/txtCountries"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

The following code snippet shows how to use the AutoCompleteTextView:

package net.learn2develop.autocomplete;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter; ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.