【发布时间】:2017-01-05 12:37:58
【问题描述】:
嗨,我正在开发一个应用程序,我在 fregement 中实现了回收器视图和搜索视图。我根据文本更改第一次获得过滤器产品。 但是当我一一删除文本时,所有列表都是空的。最后什么都不能显示。
这是我的片段中的代码
【问题讨论】:
-
使用this通用适配器
标签: android filter android-recyclerview searchview
嗨,我正在开发一个应用程序,我在 fregement 中实现了回收器视图和搜索视图。我根据文本更改第一次获得过滤器产品。 但是当我一一删除文本时,所有列表都是空的。最后什么都不能显示。
这是我的片段中的代码
【问题讨论】:
标签: android filter android-recyclerview searchview
我认为问题出在 filter 方法的 if (text.isEmpty()) { 块中。
在这里清除plistarray 列表并将空列表添加到plistarray.addAll(plistarray);
改为为 plistarray.addAll(); 添加您的 原始数据列表,这将解决您的空列表问题。
记住这一点,当你执行搜索时,总是首先在适配器的构造函数中创建一个原始列表的虚拟/副本,然后使用这个虚拟来恢复数据。
希望,这会解决您的问题。
【讨论】:
正如我所见,主要问题是您正在操纵填充适配器的 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();
}
【讨论】:
您一直在使用名为 plistarray 的单个 array 进行操作
在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();
}
【讨论】: