recycleview 中的 Diffutil,如果添加新项目,则使其自动滚动 [英] Diffutil in recycleview, making it autoscroll if a new item is added

查看:21
本文介绍了recycleview 中的 Diffutil,如果添加新项目,则使其自动滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们使用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.

推荐答案

您有一个 dispatchUpdatesTo(ListUpdateCallback) 方法也可以使用.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆