recycleview中的Diffutil,如果添加了新项目,则使其自动滚动 [英] Diffutil in recycleview, making it autoscroll if a new item is added
问题描述
如果我们使用DiffUtil.Callback
并执行
adapter.setItems(itemList);
diff.dispatchUpdatesTo(adapter);
我们如何确保添加新元素将滚动到该新位置.
how can we make sure that adding of new elements will scroll to that new position.
在某些情况下,我看到项目消失,并且在顶部的第一个元素中创建了一个新项目,但该项目不可见.它一直隐藏在顶部,直到您向下滚动使其可见为止.
在使用DiffUtil
之前,我是手动实现的,在知道要插入某个位置(在顶部)后,我可以滚动到.
I have a case where I see item disappear, and a new one is created as a first element at the top, but not visible. It is hidden on top until you scroll down to make it visible.
Before using DiffUtil
, I was implementing this manually, and after I knew I was inserting at some position (on top) I could scroll to.
推荐答案
You have a dispatchUpdatesTo(ListUpdateCallback)
method to use as well.
所以您只需实现ListUpdateCallback
即可为您插入的第一个元素
So you could just implement a ListUpdateCallback
which gives you the first element inserted
class MyCallback implements ListUpdateCallback {
int firstInsert = -1;
Adapter adapter = null;
void bind(Adapter adapter) {
this.adapter = adapter;
}
public void onChanged(int position, int count, Object payload) {
adapter.notifyItemRangeChanged(position, count, payload);
}
public void onInserted(int position, int count) {
if (firstInsert == -1 || firstInsert > position) {
firstInsert = position;
}
adapter.notifyItemRangeInserted(position, count);
}
public void onMoved(int fromPosition, int toPosition) {
adapter.notifyItemMoved(fromPosition, toPosition);
}
public void onRemoved(int position, int count) {
adapter.notifyItemRangeRemoved(position, count);
}
}
,然后手动滚动RecyclerView
myCallback.bind(adapter)
adapter.setItems(itemList);
diff.dispatchUpdatesTo(myCallback);
recycler.smoothScrollToPosition(myCallback.firstInsert);
这篇关于recycleview中的Diffutil,如果添加了新项目,则使其自动滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!