How to use AutoCompleteTextView with RecyclerView.Adapter but not with ArrayAdapter in android

后端 未结 1 1190
情歌与酒
情歌与酒 2021-02-07 13:56

I have a condition where auto suggest need to be implemented. For that purpose, I have been trying to use the custom RecyclerView.Adapter.But the problem is,AutoCompleteTextView

1条回答
  •  悲哀的现实
    2021-02-07 14:17

    AutoCompleteTextView requires a ListAdapter that is also Filterable. You can implement this by having a wrapper class around a RecyclerView.Adapter that extends BaseAdapter and delegates calls to the underlying RecyclerView.Adapter. Here's an example:

    public class RecyclerBaseAdapter 
        extends BaseAdapter implements Filterable {
    
        private final RecyclerView.Adapter mAdapter;
    
        public RecyclerBaseAdapter(RecyclerView.Adapter adapter) {
            mAdapter = adapter;
        }
    
        @Override
        public int getItemViewType(int position) {
            return mAdapter.getItemViewType(position);
        }
    
        @Override
        public int getCount() {
            return mAdapter.getItemCount();
        }
    
        @Override
        public Object getItem(int position) {
            // not supported
            return null;
        }
    
        @Override
        public long getItemId(int position) {
            return mAdapter.getItemId(position);
        }
    
        @SuppressWarnings("unchecked")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            VH holder;
            if (convertView == null) {
                holder = mAdapter.createViewHolder(parent, getItemViewType(position));
                convertView = holder.itemView;
                convertView.setTag(holder);
            } else {
                holder = (VH) convertView.getTag();
            }
            mAdapter.bindViewHolder(holder, position);
            return holder.itemView;
        }
    
        @Override
        public Filter getFilter() {
            // TODO: return a real filter
            return null;
        }
    }
    

    Now you can do mAutoCompleteTextView.setAdapter(new RecyclerBaseAdapter(mRecyclerViewAdapter)). I only tested this on a Spinner, but it should also work for your case.

    0 讨论(0)
提交回复
热议问题