Android AutoCompleteTextView Example Tutorial

AutocompleteTextView is an editable text view that shows completion suggestions automatically while the user is typing in android apps. In this tutorial we’llimplement android AutoCompleteTextView in our application using an ArrayAdapter to define the list of suggestions.

Android AutoCompleteTextView Overview

AutoCompleteTextView is a component used to show suggestions while writing in an editable text field. The suggestions list is shown in a drop down menu from which a user can select the desired item. The list of suggestions is obtained from an adapter and it appears only after a number of characters that are specified in the threshold.

In order to use an AutoCompleteThreshold field, it needs to be defined in the xml layout as follows:

Note : android:ems or setEms(x) sets the width of a TextView to fit a text of x ‘M’ number of letters regardless of the actual text extension and text size.

Some important methods of Autocomplete list are given below:

  1. getAdapter() : This method returns a filterable list adapter used for auto completion
  2. getCompletionHint() : This method returns optional hint text displayed at the bottom of the the matching list
  3. getDropDownAnchor() : This method returns returns the id for the view that the auto-complete drop down list is attached to
  4. getListSelection() : This method returns the position of the dropdown view selection, if there is any
  5. isPopupShowing() : This method indicates whether the popup menu is showing
  6. setText(CharSequence text, boolean filter) : This method sets text except that it can disable filtering
  7. showDropDown() : This method displays the drop down on screen

The setAdapter method is used to set the adapter of the autoCompleteTextView.

Let’s jump to the coding part of it.

Android AutoCompleteTextView Project Structure

android-autocomplete-project-structure-236x450

This project contains a simple TextView and a AutoCompleteTextView in the layout of the MainActivity. The ArrayAdapter contains the following fruits : Apple, Banana, Cherry, Date, Grape, Kiwi, Mango, Pear.

Android AutoCompleteTextView Example Code

The layout of the MainActivity is defined as follows.

activity_main.xml

The MainActivity.java is defined below.

In the above code, we’ve stored the list of fruits in an ArrayAdapter with a layout imported from the Android SDK.

The text color in the editable TextView is red. A threshold count of 1 depicts that to show the autocomplete drop-down list we need to type in at least one character.

Note: Autocomplete list is visible only when the Editable field is focused.

Below is our auto complete example application in execution.

Android AutoCompleteTextView Example App

This brings an end to Android AutoCompleteTextView tutorial. You can download the final Android AutoComplete project from the link given below.

By admin

Leave a Reply

%d bloggers like this: