Ali Zaidi
Ali Zaidi

Reputation: 317

How to make some items of AutoCompleteTextView suggestion un-selectable in android

I am working on a project which require me to develop a autocomplete input suggestion box the problem is the suggestion items are categorized they each category is supposed to be highlighted and unclickable. I have implemented custom ArrayAdapter for this purpose but could't figure out how to make categories un clickable here is my custom array adapter code

public class CustomAutoCompleteAdapter extends ArrayAdapter<String> {
    private static final int TYPE_ITEM = 0;
    private static final int TYPE_CATEGORY = 1;
    private TreeSet<Integer> sectionHeader = new TreeSet<Integer>();
    private LayoutInflater mInflater;


    public CustomAutoCompleteAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<String> objects) {
        super(context, resource, objects);
        mInflater = LayoutInflater.from(context);
    }
    public int getItemViewType(int position) {
        return sectionHeader.contains(position) ? TYPE_CATEGORY : TYPE_ITEM;
    }

    public void addHeader(String item) {
        super.add(item);
        sectionHeader.add(this.getCount() - 1);
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView==null){
            int type = getItemViewType(position);
            holder = new ViewHolder();
            if(type == TYPE_ITEM){
                convertView = mInflater.inflate(R.layout.item_layout,null);
                holder.textView = (TextView) convertView.findViewById(R.id.text);
            }
            else{
                convertView = mInflater.inflate(R.layout.category_layout,null);
                holder.textView = (TextView) convertView.findViewById(R.id.category);
                convertView.setClickable(false);
            }
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.textView.setText(this.getItem(position));

        return convertView;
    }
    private static class ViewHolder {
        public TextView textView;
    }

}

Upvotes: 0

Views: 287

Answers (2)

Zohaib Hassan
Zohaib Hassan

Reputation: 984

Try to remove focus from view by setting your convertview and textview both "unfocusable()". like this:

convertView.setFocusable(false);
holder.textview.setFocusable(false);

Hope it'll work!

Upvotes: 0

Ferdous Ahamed
Ferdous Ahamed

Reputation: 21756

In your CustomAutoCompleteAdapter, override isEnabled() method to disable view type TYPE_CATEGORY.

Add below code in your CustomAutoCompleteAdapter :

@Override
public boolean isEnabled(int position) 
{
    return ((getItemViewType(position) != TYPE_CATEGORY));
}

Hope this will help~

Upvotes: 2

Related Questions