TextField和ListContainer实现简单的模糊搜索功能

发布于 2021-1-17 11:45
浏览
0收藏

所需要的代码如下,

public class MyProvider extends RecycleItemProvider {

    private List<String> mSourceList;
    private List<String> mList;
    private NameFilter mNameFilter;

    public MyProvider(List<String> list) {
        this.mList = list;
        this.mSourceList = list;
    }

    @Override
    public int getCount() {
        return null!=mList?mList.size():0;
    }

    @Override
    public Object getItem(int i) {
        return null!=mList?mList.get(i):null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        return null;
    }

    @Override
    public TextFilter getFilter() {
        if(mNameFilter==null){
            mNameFilter = new NameFilter();
        }
        return mNameFilter;
    }

     class NameFilter extends TextFilter{

        @Override
        protected FilterResults executeFiltering(CharSequence charSequence) {
            FilterResults filterResults = new FilterResults();
            if(charSequence==null){
                filterResults.results=mSourceList;
            }else{
                List<String> filteredList= new ArrayList<>();
                for (Iterator<String> iterator = mList.iterator();iterator.hasNext();){
                    String name = iterator.next();
                    if(name.contains(charSequence)){
                        filteredList.add(name);
                    }
                }
                filterResults.results = filteredList;
            }
            return filterResults;
        }

        @Override
        protected void publishFilterResults(CharSequence charSequence, FilterResults filterResults) {
            mList = (List<String>) filterResults.results;
            if(filterResults.size>0){
                notifyDataChanged();
            }else{
                notifyDataInvalidated();
            }
        }
    }
}



textField.addTextObserver(new Text.TextObserver() {
    @Override
    public void onTextUpdated(String s, int i, int i1, int i2) {
        if(s.length()==0){
            textField.removeTextObserver(this);
            provider.getFilter().filter(s);
            provider.notifyDataChanged();
            textField.addTextObserver(this);
        }else {
            textField.removeTextObserver(this);
            provider.getFilter().filter(null);
            provider.notifyDataChanged();
            textField.addTextObserver(this);
        }
    }
});

1
收藏
回复
举报
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐