AutoComplete TextBox in Android

AutoComplete TextBox in Android

In this article I am going to explain how to create an AutoComplete textbox by using AutoCompleteTextView widget in an Android application. In this article I am going to create AutoCompleteTextView widget that provides suggestions for student names.

· Start a new project named AutoCompleteDemo.

· Create a XML file named list_item.xml and insert the following code in the xml.

<?xml version="1.0"encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:padding="10dp"

android:textSize="16sp"

android:textColor="#000">

</TextView>

This file simple define a TextView that will be used for each item that appears in the list of suggestions.

· Open the res/layout/main.xml and add an AutoCompleteTextView widget inside the linear layout.

After the content view is set to the main.xml layout, the AutoCompleteTextView() widget is captured from the layout with findViewById(int). Then we get all the student names in an array from the resource file. A new array adapter is then initialized to bind the list_item.xml layout to each list in the names string array. Then setAdpater() is called to associate the ArrayAdapter with the AutoCompleteTextView widget so that the string array will populate the list of suggestions.

· Run the application. The output look something like below:

When the users press some keyword, it will display the related student names automatically from the resource file.