简体   繁体   English

如何为Android ListView实现过滤器

[英]How to implement filter for android listview

I have array of model object data, and i am displaying the text and image in listview from the model object array in my custom ArrayAdapter. 我有模型对象数据的数组,并且正在自定义ArrayAdapter中从模型对象数组的listview中显示文本和图像。

Its like android contact view, i want to implement the search functionality. 它像android联系人视图一样,我想实现搜索功能。

Can any one please advice me, how to implement filter for custom adapter which shows data from model object. 谁能建议我,如何为显示模型对象数据的自定义适配器实现过滤器。

Sample example link or snippet of code is also fine. 示例示例链接或代码段也可以。

You just have to filter underlying collection ( like this: What is the best way to filter a Java Collection? ) 您只需要过滤基础集合(像这样: 过滤Java集合的最佳方法是什么?

When filter condition changes, you just signal that dataset is changed and use filtered list instance to provide amount of entries and individual views 当过滤条件发生变化时,您仅表示已更改数据集,并使用过滤后的列表实例来提供条目数量和单个视图

I actually don't like the approach where you duplicate your original list. 我实际上不喜欢您复制原始列表的方法。 It is both time consuming and memory consuming. 这既浪费时间又消耗内存。 I took the approach of just making the wanted items VISIBLE and the unwanted items GONE. 我采取的方法只是使需要的物品可见而不再需要的物品。 My example is for a TableLayout where I filter the TableRows, each has a TextView. 我的示例是针对TableLayout的,其中我过滤了TableRows,每个都有一个TextView。

public void filter(TableLayout tl, String regex) {
    TableRow tr;
    TextView tv;
    Pattern p;
    Matcher m;

    p = Pattern.compile(regex);
    int n = tl.getChildCount();
    for(int i = 0; i < n; i++) {
        tr = (TableRow) tl.getChildAt(i);
        tv = (TextView) tr.getChildAt(0);
        m = p.matcher(tv.getText());
        if(m.find()) {
            tr.setVisibility(View.VISIBLE);
        } else {
            tr.setVisibility(View.GONE);
    }
}

I did not profile it, but I am quite sure it is faster than copying all elements of a list and then filtering and then displaying the new list. 我没有对其进行概要分析,但是我确信它比复制列表的所有元素然后进行过滤然后显示新列表要快。

The advantage should be more noticeable as your list grows larger. 随着列表的增加,优点应该更加明显。

But, a caveat, I have to confess that although it works very well filtering a few hundreds of rows, I am concerned what happens when the number of rows is so big that it takes more than 5 sec to do the filtering. 但是,需要说明的是,我不得不承认,尽管它可以很好地过滤数百行数据,但是我担心当行数太大而需要5秒钟以上的时间进行过滤时会发生什么。 It should then trigger the App not responding dialog. 然后它将触发应用程序无响应对话框。
I tried to make it a thread, but because I directly deal with the views visibility I get an error message that only the original thread can touch the views. 我尝试将其设置为线程,但由于直接处理视图的可见性,因此收到一条错误消息,即只有原始线程才能触摸视图。 I am working on it and I am sure I will find a solution. 我正在努力,我相信我会找到解决方案的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM