top of page

Learn Android App Dev: Using Auto-Complete TextView

Hey there! This is Amey Lokhande. In this post, I'll be talking about how to use Auto-Complete TextView box. Generally, Auto-Complete TextView box is used when someone needs some suggestions based on the text they enter in the Text box. You can also set some ItemOnClickListener method for the item which will be clicked and what to do after it is clicked.

For ex, if you are entering some names starting with "C" and if you need some suggestions on it, then Auto-Complete Text box does this job very efficiently.

So, here are the steps on how to use Auto-Complete TextView:

1. First of all, drag a Auto-Complete TextView in your layout.

2. Now, you have to write a simple code for this Auto-Complete TextView to work. So now lets design the Java code.

3. So, first of all declare AutoComplete TextView variable and a string array for storing the names of People starting with "A". Here I am creating a Auto-Complete TextView which will work when we enter something starting with "A".

4. Now in the OnCreate method, link the Auto-Complete TextView with its ID. And then we declare an Array Adapter which will be used to show the names from the Array in the Auto-Complete TextView.

5. Now, we set the text in the Auto-Complete TextView box. The setThreshold does the job of showing the suggestions after a specific number of characters we enter in it. For ex, if setThreshold(2) will show the suggestions after we have entered 2 characters in it.

6. Now your app is ready to run.

Java Code:

package com.example.ameylokhande.autocomplete;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView;

public class MainActivity extends AppCompatActivity { private static AutoCompleteTextView actv; String[] names = {"Amey", "Ashu", "Arjun", "Ash", "Amit", "Adhiraj", "Avanti", }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

actv = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView); ArrayAdapter arr_adapt = new ArrayAdapter(this,android.R.layout.select_dialog_item,names); actv.setThreshold(2); actv.setAdapter(arr_adapt); }

}

Here's a screenshot of the working app:

Well this is it! Thanks for reading!!

Stay tuned for further updates.

bottom of page