【问题标题】:Searchview that filters a listview, with custom listview_items使用自定义 listview_items 过滤列表视图的搜索视图
【发布时间】:2015-08-24 20:16:59
【问题描述】:

我的应用有一个自定义的 ListView-Adapter,它可以将一个 listview_item 膨胀,它有多个 TextView 到一个 ListView 中。

我在布局中添加了一个 SearchView,但我想要它,以便它可以搜索 ListView 并通过查看在 SearchView 中键入的数据是否与来自 listview_items 的 TextView 中的任何数据相同来过滤它。

【问题讨论】:

  • 在 SearchView 上使用 TextWatcher,然后获取搜索词并在迭代数据集时使用它与您的数据进行比较。
  • @inner_class7 你能给个代码示例吗?我发现很难想象你的意思。不过感谢您的评论。

标签: android listview android-listview filter searchview


【解决方案1】:

在您的活动类中覆盖 OnQueryTextListener,例如:

@Override
public boolean onQueryTextChange(String newText) {
    mAdapter.getFilter().filter(newText);
    return true;
}

@Override
public boolean onQueryTextSubmit(String query) {
    mAdapter.getFilter().filter(query);
    return true;
}

在适配器内部,实现过滤器:

public Filter getFilter() {
    if (mFliter == null)
        mFliter = new CustomFilter();
    return mFliter;

}
    private class CustomFilter extends Filter {
        // called when adpater filter method is called
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            constraint = constraint.toString().toLowerCase();
            FilterResults result = new FilterResults();
            if (constraint != null && constraint.toString().length() > 0) {
                ArrayList<CustomObject> filt = new ArrayList<CustomObject>(); //filtered list
                for (int i = 0; i < originalList.size(); i++) {
                    CustomObject m = originalList.get(i);
                    if (m.getName().toLowerCase().contains(constraint)) {
                        filt.add(m); //add only items which matches
                    }
                }
                result.count = filt.size();
                result.values = filt;
            } else { // return original list
                synchronized (this) { 
                    result.values = originalList;
                    result.count = originalList.size();
                }
            }
            return result;
        }

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
            if (results != null) {
                setList((ArrayList<CustomObject>) results.values); // notify data set changed
            } else {
                setList((ArrayList<CarObject>) originalList);
            }
        }
    }

    public void setList(ArrayList<CarObject> data) {
        mList = data; // set the adapter list to data
        YourAdapter.this.notifyDataSetChanged(); // notify data set change
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多