Android Filter类

1. Filter类

Filter过滤器,一般用于搜索。
自定义SearchFilter类继承android.widget.Filter,实现performFiltering(CharSequence)publishResults(CharSequence, FilterResults)两个方法。performFiltering(CharSequence)方法用来查找数据,publishResults(CharSequence, FilterResults)方法用来展示数据。

private class SearchFilter extends Filter {
    private List mTextList = new ArrayList<>();

    public SearchFilter() {
        mTextList.add("abc");
        mTextList.add("abd");
        mTextList.add("abe");
        mTextList.add("acd");
        mTextList.add("acde");
        mTextList.add("ace");
        mTextList.add("bcd");
        mTextList.add("bce");
        mTextList.add("bcf");
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        // FilterResults用来保存过滤结果,包含两个属性values和count
        FilterResults results = new FilterResults();

        List resultList = new ArrayList<>();
        for (String text : mTextList) {
            if (constraint != null && constraint.length() > 0
                    && text.contains(constraint)) {
                resultList.add(text);
            }
        }

        results.values = resultList;
        results.count = resultList.size();

        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        mAdapter.clear();
        if (results.count > 0) {
            mAdapter.addAll((List)results.values);
        }
    }
}

2. 搜索界面

搜索界面包含一个搜索输入框,和搜索结果列表。调用filter(CharSequence)方法进行过滤。




    

    


设置EditTextTextWatcher监听器

EditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mFilter.filter(mEtInput.getText().toString());
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
});

效果如下
Android Filter类_第1张图片

你可能感兴趣的:(Android,特性)