【发布时间】:2016-07-29 10:55:36
【问题描述】:
我想要 android 中 MVP 结构的简单示例来刷新 recyclerview 项目而不是 recyclerview 的整个列表。
它只会刷新android的recyclerview中的项目。
【问题讨论】:
标签: android android-recyclerview mvp
我想要 android 中 MVP 结构的简单示例来刷新 recyclerview 项目而不是 recyclerview 的整个列表。
它只会刷新android的recyclerview中的项目。
【问题讨论】:
标签: android android-recyclerview mvp
这是一个我想了很多的问题。有两种可能的方法:
ListChangeItems 发送到适配器。我将在下面更详细地概述两者。在这两种情况下,您都需要计算当前显示的数据与新数据之间的差异。我有一个帮助类 ListDiffHelper<T> 进行比较:
public class ListDiffHelper<T> {
private List<T> oldList;
private List<T> newList;
private List<Integer> inserted = new ArrayList<>();
private List<Integer> removed = new ArrayList<>();
public List<Integer> getInserted() {return inserted;}
public List<Integer> getRemoved() {return removed;}
public ListDiffHelper(List<T> oldList, List<T> newList) {
this.oldList = oldList;
this.newList = newList;
checkForNull();
findInserted();
findRemoved();
}
private void checkForNull() {
if (oldList == null) oldList = Collections.emptyList();
if (newList == null) newList = Collections.emptyList();
}
private void findInserted() {
Set<T> newSet = new HashSet<>(newList);
newSet.removeAll(new HashSet<>(oldList));
for (T item : newSet) {
inserted.add(newList.indexOf(item));
}
Collections.sort(inserted, new Comparator<Integer>() {
@Override
public int compare(Integer lhs, Integer rhs) {
return lhs - rhs;
}
});
}
private void findRemoved() {
Set<T> oldSet = new HashSet<>(oldList);
oldSet.removeAll(new HashSet<>(newList));
for (T item : oldSet) {
removed.add(oldList.indexOf(item));
}
Collections.sort(inserted, new Comparator<Integer>() {
@Override
public int compare(Integer lhs, Integer rhs) {
return rhs - lhs;
}
});
}
}
要使其正常工作,您需要确保 Data 类的 equals() 方法以合适的方式比较事物。
适配器主管
在这种情况下,您的 Presenter 在模型上调用 getData()(或者如果您使用 Rx,则订阅它)并接收 List<Data>。然后它通过setData(data) 方法将此列表传递给视图,该方法又将列表提供给适配器。适配器中的方法类似于:
private void setData(List<Data> data) {
if (this.data == null || this.data.isEmpty() || data.isEmpty()) {
this.data = data;
adapter.notifyDataSetChanged();
return;
}
ListDiffHelper<Data> diff = new ListDiffHelper<>(this.data, data);
this.data = data;
for (Integer index : diff.getRemoved()) {
notifyItemRemoved(index);
}
for (Integer index : diff.getInserted()) {
notifyItemInserted(index);
}
}
在添加新项目之前先删除项目很重要,否则订单将无法正确维护。
模型主管
另一种方法是让适配器变得更笨,并计算模型层中发生的变化。然后,您需要一个包装类将各个更改发送到您的视图/适配器。比如:
public class ListChangeItem {
private static final int INSERTED = 0;
private static final int REMOVED = 1;
private int type;
private int position;
private Data data;
public ListChangeItem(int type, int position, Data data) {
this.type = type;
this.position = position;
this.data = data;
}
public int getType() {return type;}
public int getPosition() {return position;}
public Data getData() {return data;}
}
然后您将通过视图界面将这些列表传递给您的适配器。同样重要的是在插入之前执行删除操作,以确保数据的顺序正确。
【讨论】: