如果您在您的适配器有稳定的ID,您可以得到相当不错的效果(动画)如果您创建一个新的数组包含经过滤项,并调用
recyclerView.swapAdapter(newAdapter, false);
使用swapAdapter提示RecyclerView之能重复使用查看者。 (与setAdapter相比,它必须回收所有视图并重新创建,因为它不知道新适配器与旧适配器设置了相同的ViewHolder)。
更好的方法是找到哪些项目被删除,并呼吁notifyItemRemoved(index)
。不要忘记实际移除物品。这将让RecyclerView运行预测动画。假设你有一个内部使用一个ArrayList的适配器,实现应该是这样的:
// adapter code
final List<ItemData> mItems = new ArrayList(); //contains your items
public void filterOut(String filter) {
final int size = mItems.size();
for(int i = size - 1; i>= 0; i--) {
if (mItems.get(i).test(filter) == false) {
mItems.remove(i);
notifyItemRemoved(i);
}
}
}
它会执行,如果你可以批量notifyItemRemoved
调用和使用notifyItemRangeRemoved
,而不是更好。它看起来某事像:(未测试)
public void filterOut(String filter) {
final int size = mItems.size();
int batchCount = 0; // continuous # of items that are being removed
for(int i = size - 1; i>= 0; i--) {
if (mItems.get(i).test(filter) == false) {
mItems.remove(i);
batchCount ++;
} else if (batchCount != 0) { // dispatch batch
notifyItemRangeRemoved(i + 1, batchCount);
batchCount = 0;
}
}
// notify for remaining
if (batchCount != 0) { // dispatch remaining
notifyItemRangeRemoved(0, batchCount);
}
}
你需要扩展该代码添加先前过滤掉的项目,但现在应该是可见的(例如,用户删除过滤查询),但我觉得这个应该给出基本的想法。
请记住,每个通知项目调用会影响后面的项目(这就是为什么我要从尾遍历列表以避免它)。从最后遍历也有助于ArrayList的删除方法的性能(更少的项目转移)。
例如,如果您从头开始遍历列表并删除前两个项目。 你应该调用
notifyItemRangeRemoved(0, 2); // 2 items starting from index 0
,或者如果你发货,由一个
notifyItemRemoved(0);
notifyItemRemoved(0);//because after the previous one is removed, this item is at position 0
如果你想给另一个数组你可以创建一个新的'ItemsAdapter'它并再次调用'setAdapter'。 – 2014-10-29 16:44:09