回收视图在第一次加载时自动滚动到内部回收视图
Recycler View automatically scrolls to inner recycler view on first load
我有根垂直回收器视图和项目
- ViewPager
- 水平回收器视图
- 水平回收器视图 ...
首次加载数据时,当入口动画停止时,根回收器视图略微滚动,第二项(回收器视图)完全可见。
为什么会这样?以及如何避免这种自动滚动。
当您调用 notifyDataSetChanged
或 notifyItemsInserted
时,它会触发 RecyclerView
中的 requestLayout
。
布局后,RecyclerView
尝试recoverFocusFromState
。当它找到第一个可聚焦的 child 时,它会尝试将其完全显示在视野中。如果可聚焦 child 在布局结束时部分可见,则会导致滚动并且可聚焦 child 将完全可见。
在上面的例子中,child RecyclerView
就是 focusable
child。 ProgressBar
或任何其他 focusable
视图
也会发生同样的情况
解决方案 1
如果您知道您的 child 视图不可聚焦。您可以添加
android:descendantFocusability="blocksDescendants"
到你的根 RecyclerView
解决方案 2
将 focusable="false"
添加到您的不可聚焦 childs
你可以试试这些;
- 将
android:descendantFocusability="blocksDescendants"
添加到您的父布局或 recyclerview
- 将
android:focusableInTouchMode="true"
添加到您的父布局或 recyclerview
- 不是一个好的解决方案,但也许现在您可以尝试:
recyclerView.scrollToPosition(0)
使用在此问题上发布的解决方案 https://github.com/airbnb/epoxy/issues/224
这是对我有用的代码片段
recyclerview.getAdapter().registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
if(positionStart == 0) {
(recyclerview.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(positionStart,0)
}
}
});
我有根垂直回收器视图和项目
- ViewPager
- 水平回收器视图
- 水平回收器视图 ...
首次加载数据时,当入口动画停止时,根回收器视图略微滚动,第二项(回收器视图)完全可见。
为什么会这样?以及如何避免这种自动滚动。
当您调用 notifyDataSetChanged
或 notifyItemsInserted
时,它会触发 RecyclerView
中的 requestLayout
。
布局后,RecyclerView
尝试recoverFocusFromState
。当它找到第一个可聚焦的 child 时,它会尝试将其完全显示在视野中。如果可聚焦 child 在布局结束时部分可见,则会导致滚动并且可聚焦 child 将完全可见。
在上面的例子中,child RecyclerView
就是 focusable
child。 ProgressBar
或任何其他 focusable
视图
解决方案 1
如果您知道您的 child 视图不可聚焦。您可以添加
android:descendantFocusability="blocksDescendants"
到你的根 RecyclerView
解决方案 2
将 focusable="false"
添加到您的不可聚焦 childs
你可以试试这些;
- 将
android:descendantFocusability="blocksDescendants"
添加到您的父布局或 recyclerview - 将
android:focusableInTouchMode="true"
添加到您的父布局或 recyclerview - 不是一个好的解决方案,但也许现在您可以尝试:
recyclerView.scrollToPosition(0)
使用在此问题上发布的解决方案 https://github.com/airbnb/epoxy/issues/224 这是对我有用的代码片段
recyclerview.getAdapter().registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
if(positionStart == 0) {
(recyclerview.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(positionStart,0)
}
}
});