How to use autocompletetextview with example to show suggestions ? - SpartaCode

SpartaCode

Make your development faster and easier !

How to use autocompletetextview with example to show suggestions ?


Auto Suggestion EditText or AutoCompleteTextView
Whenever User has long list of items and he needs to select one item from it, we can use AutocompleteTextView to provide suggestions to User regarding characters he types into TextBox.
To provide such kind of suggestions we use AutoCompleteTextView.

In this tutorial we will learn how to get ID of item selected by User in AutoCompleteTextView and instead of using String Adapter we will use CustomAdapter to design the View of suggestion list which will be displayed when user types into AutoCompleteTextView(Which behaves like Edittext).

Step By Step Quick Tutorial On AutoCompleteTextView:

Step 1: Make Layout
Copy paste this into your layout file(.xml corresponding to java)
        
 <AutoCompleteTextView
                android:id="@+id/et_itemname"
            style="@android:style/TextAppearance.DeviceDefault.Medium"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginTop="10dp"
                android:background="@drawable/edittext_style"
                android:drawablePadding="5dp"
                android:hint="Item name"
                android:inputType="textPersonName"
                android:padding="10dp" />

Create drawable with name edittext_style.xml and paste following:
<?xml version="1.0" encoding="utf-8" ?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:thickness="0dp"
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <gradient
        android:startColor="#DDD"
        android:endColor="#DDD"
        android:type="linear"
        android:angle="270"/>
</shape>

Create new Layout File and copy paste following code: 
row_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:foo="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:padding="10dp"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Item name"
            android:textColor="#000"
            android:textSize="20dp"
            />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tv_rate"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:text="Company"
            android:textSize="20dp"
            android:textColor="#000"

            />

    </RelativeLayout>


    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorPrimary"
        android:layout_marginTop="5dp"
        />

</LinearLayout>

Step 2: Creating Model Class and Adapter :
Creating Model Class: 
What is Model Class ?
Model class holds all attributes required by a single object.
For Example :
A User will have Model class named User with following attributes :
1. Name
2. Address
3. Contact, etc.
You can easily create your model class using following website :
Create Model class by providing required attributes in JSON format as follows :


After Creating Model Class, Create New Java Class in Android Studio and paste Model class into it.

Creating Custom Adapter:
Once you have created Model class Next Step is to create Custom Adapter to display suggestions

To create Custom Adapter create New Class and paste following code:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;


public class CustomSuggestionAdapter extends ArrayAdapter {
    Context mContext;
    ArrayList list=new ArrayList<>();
    private int lastPosition = -1;
    ArrayList  tempCustomer, suggestions ;

    public CustomSuggestionAdapter(Context context , ArrayList data) {
        super(context, R.layout.row_item, data);
        this.mContext=context;
        list=data;
        this.tempCustomer =new ArrayList<>(data);
        this.suggestions =new ArrayList<>(data);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
            final Item dataModel = list.get(position);
            // Check if an existing view is being reused, otherwise inflate the view
            ViewHolder viewHolder = new ViewHolder();; // view lookup cache stored in tag

            if(convertView == null){
                LayoutInflater inflater = LayoutInflater.from(getContext());
                convertView = inflater.inflate(R.layout.row_item, parent, false);
                viewHolder.tv_name=convertView.findViewById(R.id.tv_name);
                viewHolder.tv_rate=convertView.findViewById(R.id.tv_rate);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) convertView.getTag();
            }


            viewHolder.tv_name.setText(dataModel.getItemname());
            viewHolder.tv_rate.setText(dataModel.getItemRate());

        return convertView;
    }

    // View lookup cache
    private static class ViewHolder {
        TextView tv_name,tv_rate;
    }

    @Override
    public Filter getFilter() {
        return myFilter;
    }

    Filter myFilter = new Filter() {
        @Override
        public CharSequence convertResultToString(Object resultValue) {
            Item item = (Item) resultValue;
            Toast.makeText(mContext,"Selected Item "+item.getItemname(),Toast.LENGTH_LONG).show();
            return item.getItemname();
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            if (constraint != null) {
                suggestions.clear();
                for (Item item : tempCustomer) {
                    if (item.getItemname().toLowerCase().startsWith(constraint.toString().toLowerCase()) ||
                            item.getItemRate().toLowerCase().startsWith(constraint.toString().toLowerCase()) ) {
                        suggestions.add(item);
                    }
                }

                FilterResults filterResults = new FilterResults();
                filterResults.values = suggestions;
                filterResults.count = suggestions.size();
                return filterResults;
            } else {
                return new FilterResults();
            }
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            ArrayList c = (ArrayList) results.values;
            if (results != null && results.count > 0) {
                clear();
                for (Item item : c) {
                    add(item);
                    notifyDataSetChanged();
                }
            }
            else{
                clear();
                notifyDataSetChanged();
            }
        }
    };
}




Step 3: Implementing into your Activity
Finally we implement into activity we want to use by declaring AutocompleteTextView and ArrayList to hold Item data.

Declaration:
    ArrayList itemArrayList;
    AutoCompleteTextView et_itemname;

Initialization of ArrayList and AutoCompleteTextView:
        itemArrayList=new ArrayList<>();

        //Adding static element into list
        Item item1=new Item();
        item1.setItemname("Apple");
        item1.setItemRate("200 Rs");
        itemArrayList.add(item1);

        Item item2=new Item();
        item1.setItemname("Pinaple");
        item1.setItemRate("100 Rs");
        itemArrayList.add(item2);

        CustomSuggestionAdapter itemSuggestionCustomerAdapter =new CustomSuggestionAdapter(getApplicationContext(),itemArrayList);
        et_itemname.setAdapter(itemSuggestionCustomerAdapter);
        et_itemname.setThreshold(0);

Finally Run the Project and you will see following output:


In this way we learnt how to get ID of single Item when it is selected by User. There are many applications of this feature, this feature improves the usability of your app.
When ever you need auto suggestion code you can visit again and help me make more such easy and fast tutorials on Programming.

Thank You for your Visit
If you like post, Please Share and Comment.

2 comments:

  1. Great Article on AutocompleteTextView with Custom Suggestion view. Thank you Ankit.

    ReplyDelete
  2. Really super tutorial! i was searching for custom suggestion and i end up here with great satisfaction. Thank you.

    ReplyDelete

Get Amazing Traffic to your Site

Traffic Exchange

Post Bottom Ad

Responsive Ads Here