搜索视图与回收站视图不正常工作

3

你好,我正在开发一款应用程序,其中我在片段中实现了RecyclerView和SearchView。在文本更改时,我第一次获取过滤产品。但是当我逐个删除文本时,所有列表都将为空。最后没有任何内容可以显示。

这是来自我的片段的代码:


使用此通用适配器[MatchableRVArrayAdapter(纯RecyclerView样式,无隐式TextView映射)]进行编程。 - pskink
3个回答

2

您正在持续操作名为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
请检查@unknown apk,同时参考代码中的注释。 - Nikhil
@unknown apk 如果我的回答有帮助到您,您可以接受它。 - Nikhil

1
我认为问题出在filter方法的if (text.isEmpty()) {块中。
在这里,您清除了plistarray列表,并将该空列表添加到plistarray.addAll(plistarray); 相反,您应该将plistarray.addAll();替换为您的原始数据列表。这将解决您的空列表问题。
请记住,在执行搜索时,始终首先在适配器的构造函数中创建一个虚拟/副本原始列表,并使用此虚拟列表来恢复数据。
希望这能解决您的问题。

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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接