如何在RecyclerView.Adapter中使用AutoCompleteTextView,但在android

时间:2015-11-14 17:46:01

标签: android-recyclerview autocompletetextview

我有条件需要实施自动建议。为此,我一直在尝试使用自定义的RecyclerView.Adapter。但问题是,AutoCompleteTextView似乎是针对BaseAdapter及其子类进行的。

因此,不接受适配器。还有其他方法,我可以使用RecyclerView适配器与AutoCompleteTextView。是ArrayListAdapter还是仅用于AutCompleteTextView的BaseAdapter解决方案?

1 个答案:

答案 0 :(得分:6)

AutoCompleteTextView要求ListAdapter也是Filterable。您可以通过在RecyclerView.Adapter周围扩展BaseAdapter并将调用委托给基础RecyclerView.Adapter来实现此目的。这是一个例子:

public class RecyclerBaseAdapter<VH extends RecyclerView.ViewHolder> 
    extends BaseAdapter implements Filterable {

    private final RecyclerView.Adapter<VH> mAdapter;

    public RecyclerBaseAdapter(RecyclerView.Adapter<VH> 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;
    }
}

现在你可以做mAutoCompleteTextView.setAdapter(new RecyclerBaseAdapter(mRecyclerViewAdapter))。我只在Spinner上对此进行了测试,但它也适用于您的情况。