当可观察项被移动时如何禁用 recyclerview 滚动 [英] How to disable recyclerview scrolling when observable item gets moved
问题描述
当我在位置 0 上有第一个回收器视图项目,然后假设 10 个项目插入位置 0 使第一个进入位置 10 的回收器视图滚动到位置 10.如何禁用此功能使回收器视图保持在顶部?
When I have first recycler view item on position 0 and then lets say 10 items get inserted on position 0 making first one go to position 10 recycler view scrolls to position 10. How to disable this functionality making recycler view stay on top?
我在下面有一个可能的答案,但它有缺点.使用这种方法 recyclerview 确实会滚动到顶部,但只有在滚动到末尾之后.这有点烦人.有谁知道如何让它在不走到最后的情况下保持领先?
I have a possible answer below, but it has disadvatanges. With this aproach recyclerview indeed will scroll to the top but only after scrolling to the end. And it's kinda annoying. Any one knows how to make it stay on top without going to the end?
推荐答案
我遇到了完全相同的问题 - 当我的 LiveData
和我的 >
recyclerview
以这样一种方式显示更新,即第一个项目改变了位置,它总是会滚动到该项目的新位置(但如果除第一个项目以外的任何其他项目被移动,则不会).我找到了一个相对简单的解决方案.在带有 recylcerview
的 fragment
中显示你的 LiveData
,你大概有这样的代码:
I had the exact same problem - for me when my LiveData<List<Item>>
which my recyclerview
was displaying updated in such a way that the first item changed positions, it would always scroll to the new position of that item (but not if any other item other than the first one was moved). I found a relatively simple solution. In the fragment
with the recylcerview
which displays your LiveData
, you presumably have code something like this:
myViewModel.getAllItems().observe(getViewLifeCycleOwner(), items -> {
myAdapter.setItems(items);
});
要在移动第一个项目时阻止它滚动,只需在 setItems()
方法的两侧添加这两行:
To stop it from scrolling when the first item is moved, simply add these two lines either side of the setItems()
method:
myViewModel.getAllItems().observe(getViewLifeCycleOwner(), items -> {
Parcelable recyclerViewState = myRecyclerView.getLayoutManager().onSaveInstanceState();
adapter.setItems(slItems);
myRecyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
});
如果要更改它,这似乎会恢复原始滚动位置,使 UI 保持在更改发生之前的任何滚动位置,而没有任何可察觉的移动.
This seems to restore the original scroll position if it was going to change it, making the UI stay at whatever scroll position it was at before the change occurred without any perceptible movement.
这篇关于当可观察项被移动时如何禁用 recyclerview 滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!