Android页面加载后自动滚动到RecyclerView的问题该如何解决
问题修复方案
根本原因
当前布局采用ScrollView嵌套RecyclerView的结构,页面加载完成后RecyclerView会默认抢占焦点,触发ScrollView自动滚动到RecyclerView所在位置,仅给RecyclerView设置焦点拦截属性未生效,是因为没有从父容器层面拦截焦点传递逻辑。
解决方案
1. XML布局修改
你需要对现有布局做以下几处调整:
- 给
标签添加id,同时新增3个焦点控制属性 - 给ScrollView的直接子LinearLayout添加根焦点抢占属性
- 给RecyclerView补全焦点禁用属性
修改后的完整XML如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff"> <ScrollView android:id="@+id/rootScrollView" android:layout_width="match_parent" android:layout_height="match_parent" android:focusable="true" android:focusableInTouchMode="true" android:descendantFocusability="beforeDescendants"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:focusable="true" android:focusableInTouchMode="true"> <TextView android:id="@+id/intro" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="This is a welcome text" android:textSize="15sp" android:lineSpacingExtra="5dp" android:paddingTop="10dp" android:paddingStart="8dp" android:paddingEnd="8dp" android:paddingBottom="16dp" android:textColor="#000000" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/buttonOptions"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/pathsRecyclerView" android:layout_width="match_parent" android:layout_height="match_parent" android:nestedScrollingEnabled="false" android:descendantFocusability="blocksDescendants" android:focusable="false" android:focusableInTouchMode="false" /> </RelativeLayout> </LinearLayout> </ScrollView> </LinearLayout>
2. 代码兜底处理
如果XML修改后仍偶发自动滚动,可以在Fragment的onViewCreated方法中添加以下逻辑,强制页面加载完成后滚动到顶部:
@Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ScrollView rootScrollView = view.findViewById(R.id.rootScrollView); // 等待布局渲染完成后滚动到顶部 rootScrollView.post(() -> rootScrollView.scrollTo(0, 0)); }
说明
上述方案从父容器焦点拦截、子控件焦点禁用两个维度处理焦点抢占问题,配合代码层面的兜底滚动控制,可完全解决页面启动自动滚动到RecyclerView的问题。
内容的提问来源于stack exchange,提问作者cesarcarlos
相关产品推荐
相关产品推荐

