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
收藏
回复
举报
1条回复
按时间正序
/
按时间倒序
张荣超_九丘教育
张荣超_九丘教育

要是能把运行效果的截图附上就更好了^_^

回复
2021-1-17 22:33:17
回复
    相关推荐