Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Implementing AutoCompleteTextView

Author: Rachee Singh -- Published? true -- FormatLanguage: W

Problem:

Save the user from typing entire words, instead auto-complete the entries.

Solution:

Using the widget: AutoCompleteTextView that acts as something in between EditText and a Spinner, enabling auto completion.

Discussion:

This layout includes a TextView which supports auto-completion. Auto-completion is done using a AutoTextCompleteTextView widget. Here's what the layout XML code looks like:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
	android:id="@+id/field"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	/>
	<AutoCompleteTextView 
	android:id="@+id/autocomplete"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:completionThreshold="2"/>
    
</LinearLayout>

The completionThreshold field in the AutoCompleteTextView sets the minimum number of characters that the user has to enter in the TextView so that auto-completion options corresponding to his/her inout start showing up.

The Activity (in which we are implementing auto-completion) should implement TextWatcher so we can override onTextChanged() method:

public class AutoComplete extends Activity implements TextWatcher {

We would need to override the unimplemented methods: onTextChanged, afterTextChanged and afterTextChanged.

We also require 3 fields:

  1. A handle on to the TextView
  2. A handle on to the AutoCompleteTextView
  3. A list of String items within which the auto-completion would happen.
private TextView field;
private AutoCompleteTextView autocomplete;
String autocompleteItems [] = {"apple", "banana", "mango", "pineapple","apricot", "orange", "pear", "grapes"};
@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		field.setText(autocomplete.getText());
	}

In the onCreate method of the same activity, we get a handle on the TextView and the AutoCompleteTextView components of the layout. To the AutoCompleteTextView we will set a String adapter.


setContentView(R.layout.main);
field = (TextView) findViewById(R.id.field);
autocomplete = (AutoCompleteTextView)findViewById(R.id.autocomplete);
autocomplete.addTextChangedListener(this);
autocomplete.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, autocompleteItems));

Download:

The source code for this project can be downloaded from https://docs.google.com/leaf?id=0B_rESQKgad5LYzVkOTdlOGUtODg5My00ZTRmLWIyNTYtMDdiMzA0NjhiNGRk&hl=en_US.
No records found.