Android How to Work With AutoCompleteTextView

Hello,

Recently in one of my project I have to create auto complete text view in android. In this blog I am going to explain how to work with it.

First you have to add AutoCompleteTextView in your layout XML file.

<AutoCompleteTextView  
        android:id=“@+id/autoCompleteLocationTextView”  
        android:layout_width=“fill_parent”  
        android:layout_height=“60dp”  
        android:ems=“10”  

        android:hint=“Type to Search”>
Then in your activity get reference of it.
AutoCompleteTextView  locationText = (AutoCompleteTextView)findViewById(R.id.autoCompleteLocationTextView);
Then set threshold for it.
locationText.setThreshold(1); 

Here we set threshold to 1 that means after typing first character it will show you matched suggestions. You can change it as per your requirement.

Then we have to set an adapter. Adapter is nothing but it’s a collections of your suggestions.

String[] locationListArray = {
    “Ahmedabad”,
    “Ahmednagar”,
    “Agartala”,
    “Mumbai”,
    “Noida”,
    “Kolkata”
}
ArrayAdapter adapter1 = new ArrayAdapter  
            (this,android.R.layout.select_dialog_item,locationListArray);
locationText.setAdapter(adapter1);

As you can see above we have loaded our collections in array and created adapter from it and assigned adapter to locationList. That’s it now it will show you suggestions as soon as you start typing it.

If you want to get value of it on change. You can do following.

locationText.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView arg0, View arg1, int position,
                    long arg3) {
            String item = (String)arg0.getItemAtPosition(position);
});
Hope this helps you.
This entry was posted in Android, Android App, Java, Mobile Application on by .

About Hiren Dave

Hiren Dave is a software engineer, blogger and consultant with over 9 years of professional experience. He writes code in number of languages. Hiren has a passion for developing web apps, mobile apps and writing books and blog articles about programming. He has a solid experience of startups as he manages products for few startups. He is also passionate about researching and learning new technologies and trends. He has also authored a book Instant Sencha Touch, published by Packt and creator of Video Course "Beginning Laravel" for Packt

Leave a Reply

Your email address will not be published. Required fields are marked *