带有回收站视图的searchview无法正常工作

时间:2016-08-29 12:59:15

标签: android filter android-recyclerview searchview

您正在开发一个应用程序,我在fregement.i中实现了回收站视图和searchview。根据文本更改首次获取过滤器产品。 但是当我逐个删除文本时,所有列表都将为空。最后可以显示。

这是我的代码中的代码

3 个答案:

答案 0 :(得分:2)

您持续使用名为array的单plistarray

此处filter()方法已清除plistarray并再次使用相同的方法查找记录。所以你应该为你的适配器而不是plistarray

使用其他一些数组
public void filter(String text) {
        if (text.isEmpty()) {
            plistarray.clear();
            plistarray.addAll(plistarray);
        } else {
            ArrayList<ProductList> result = new ArrayList<>();
            text = text.toLowerCase();
            //after clearing the array again you are using same array to find the items from
            for (ProductList item : plistarray) {
                if (item.getPtitle().toLowerCase().contains(text)) {
                    result.add(item);
                }
            }
             //you have cleared all the contains here
            plistarray.clear();
            // and added only result related items here
            plistarray.addAll(result);
        }
        notifyDataSetChanged();
    }

答案 1 :(得分:1)

我认为问题出在if (text.isEmpty()) {方法的filter块中 在此处清除plistarray列表,并在plistarray.addAll(plistarray);

中添加该空列表

而不是为 plistarray.addAll(); 添加原始数据列表。这将解决您的空列表问题。
记住这一点,当你执行搜索时,总是首先在适配器的构造函数中创建一个原始列表的虚拟/副本,并使用这个虚拟来恢复数据。

希望,这将解决您的问题。

答案 2 :(得分:1)

正如我所看到的主要问题是你正在操纵你的适配器填充List,但你没有原始数据集的“副本”。

这样的事情应该有效:

ArrayList<ProductList> plistarray;     // these are instance variables
ArrayList<ProductList> plistarrayCopy; // in your adapter

// ...

public void filter(String text) {
    if (plistarrayCopy == null) {
        plistarrayCopy = new ArrayList<>(plistarray);
    }

    if (text.isEmpty()) {
        plistarray.clear();
        plistarray.addAll(plistarrayCopy);
        plistarrayCopy = null;
    } else {
        text = text.toLowerCase();
        ArrayList<Device> filteredList = new ArrayList<>();

        for (ProductList pList : plistarrayCopy) {
            if (pList.getPtitle().toLowerCase().contains(text)) {
                filteredList.add(pList);
            }
        }
        plistarray.clear();
        plistarray.addAll(filteredList);
    }
    notifyDataSetChanged();
}
相关问题