Open In App

AutoCompleteTextView in Android

The AutoCompleteTextView is a type of edit text in android which gives suggestions to the user if the user types something in the AutoCompleteTextView. This type of edit text we can see while we register on some websites. If we type “In” it will suggest India, Indonesia, West Indies ….. etc. Like this, the AutoCompleteTextView works. Let us see the implementation of AutoCompleteTextView in XML and Java . Here XML is used to create the layout and java code is used to implement the main function of AutoCompleteTextView .

Step by Step Implementation

Step 1: Create a New Project



To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file



Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. This xml code creates an activity with a TextView and an AutoCompleteTextView under Linearlayout




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is AutoCompleteTextView"/>
    
    <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="100px"
        android:placeholder="Enter your country name"
        android:id="@+id/txtcountries"/>
  
</LinearLayout>

Step 3: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.




package com.example.myapplication;
  
import androidx.appcompat.app.AppCompatActivity;
  
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
  
public class MainActivity extends Activity {
    
    String[] countries={"India","Australia","West indies","indonesia","Indiana",
                        "South Africa","England","Bangladesh","Srilanka","singapore"};
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,countries);
        AutoCompleteTextView textView=(AutoCompleteTextView)findViewById(R.id.txtcountries);
        textView.setThreshold(3);
        textView.setAdapter(adapter);
    }
}

Output:

Explanation:


Article Tags :