Wednesday, September 9, 2015

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.

No comments:

Post a Comment