Tutorial

Android AutoCompleteTextView Example Tutorial

Published on August 3, 2022
author

Anupam Chugh

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’ll implement 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:

<AutoCompleteTextView
   android:id="@+id/autoCompleteTextView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentTop="true"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="65dp"
   android:ems="10" >

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 AutoCompleteTextView example project structure 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

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:text="Name a fruit from (Apple Banana Cherry Date Grape Kiwi Mango Pear)" />

    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView"
        android:layout_marginLeft="36dp"
        android:layout_marginTop="17dp"
        android:ems="10"
        android:text="">

        <requestFocus />
    </AutoCompleteTextView>

</RelativeLayout>

The MainActivity.java is defined below.

package com.journaldev.autocomplete;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class MainActivity extends Activity {
    String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Creating the instance of ArrayAdapter containing list of fruit names
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (this, android.R.layout.select_dialog_item, fruits);
        //Getting the instance of AutoCompleteTextView
        AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
        actv.setThreshold(1);//will start working from first character
        actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
        actv.setTextColor(Color.RED);

    }
}

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.

Download Android AutoCompleteTextView Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Anupam Chugh

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 9, 2021

how can we check suggestion list has a data or not and show a message according to it

- VAISAKH R

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    September 7, 2020

    Hi, I want to use AutoCompleteTextView as a spinner with binding. Do you have an example with this?

    - Oana

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      July 6, 2020

      My whole code is the same yet my program keeps on crashing and then shows ‘Your program keeps stopping’, which I don’t know why? Then when I had debug and checked it in the logcat it keeps showing error in main activity on line 16 !!! can anyone please guide me ? I’m a beginner level student of android apps.

      - Sharmeen

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 20, 2020

        Not working on Android 10. Touch events are not triggered, while, when using Android Studio, I can navigate with keyboard arrow buttons. Also, the imeMode needs to be manually set in XMl to support focus options to next EditText item.

        - Linards Liepiņš

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 9, 2019

          R.layout.select_dialog_item where is this file ??

          - Dell

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            November 12, 2018

            how to add image in the last element / object. take an example we have 5 array data , I want to add a image on 6 th elemenet / object. How we can do that?

            - HITESH

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              October 3, 2017

              add two autocompleteview and search data

              - Ranjit Shete

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                August 16, 2017

                Thanks, Anupam, it helped me a lot in learning auto complete TextView. Btw can you tell me how to implement very large amount of data in auto complete TextView.

                - Anup Das

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  April 9, 2017

                  From where did you get R.layout.select_dialog_item?

                  - syed souban

                    Try DigitalOcean for free

                    Click below to sign up and get $200 of credit to try our products over 60 days!

                    Sign up

                    Join the Tech Talk
                    Success! Thank you! Please check your email for further details.

                    Please complete your information!

                    Become a contributor for community

                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                    DigitalOcean Documentation

                    Full documentation for every DigitalOcean product.

                    Resources for startups and SMBs

                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                    Get our newsletter

                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                    New accounts only. By submitting your email you agree to our Privacy Policy

                    The developer cloud

                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                    Get started for free

                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                    *This promotional offer applies to new accounts only.