Android - 加载时屏幕自动滚动到 RecyclerView

Posted

技术标签:

【中文标题】Android - 加载时屏幕自动滚动到 RecyclerView【英文标题】:Android - Screen scrolls automatically to RecyclerView when loaded 【发布时间】:2021-10-28 16:37:35 【问题描述】:

我正在开发一个 android (Java) 应用程序。我有一个片段,上面有一个段落,下面是一个RecyclerView。当我启动应用程序并加载屏幕时,内容会滚动,以便顶部段落完全超出屏幕,并且RecyclerView 是唯一可见的内容。

按照这个解决方案:Recycler View automatically scrolls to inner recycler view on first load 我尝试添加

android:descendantFocusability="blocksDescendants"

focusable="false"

到回收站视图,但它们都不起作用。

这是片段的 XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_
    android:layout_
    android:background="#ffffff">

    <ScrollView
        android:layout_
        android:layout_>

        <LinearLayout
            android:layout_
            android:layout_
            android:orientation="vertical">

            <TextView
                android:id="@+id/intro"
                android:layout_
                android:layout_
                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_
                android:layout_
                android:layout_below="@+id/buttonOptions">

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/pathsRecyclerView"
                    android:layout_
                    android:layout_
                    android:nestedScrollingEnabled="false"
                    android:descendantFocusability="blocksDescendants"
                    />

            </RelativeLayout>



        </LinearLayout>
    </ScrollView>


</LinearLayout>

如何解决页面不自动滚动的问题?

【问题讨论】:

这可能是因为滚动视图环绕着回收器视图。当一个可滚动视图包装另一个可滚动视图时,我看到了与 android 类似的问题。您是否尝试过删除滚动视图? 你想要这样的东西:youtu.be/nUnPoxo_ZG4? 【参考方案1】:

您将android:descendantFocusability 添加到RecyclerView,尽管您需要禁用ScrollView 子级的焦点功能,因为这种自动滚动是由ScrollView 引起的,而不是RecyclerView .

因此,要解决此问题,您需要将 android:descendantFocusability="blocksDescendants"RecyclerView 转移到 ScrollView 的直接子代,即 LinearLayout

<ScrollView
    android:layout_
    android:layout_>

    <LinearLayout
        ....
        android:descendantFocusability="blocksDescendants">

        <TextView
           ...

【讨论】:

以上是关于Android - 加载时屏幕自动滚动到 RecyclerView的主要内容,如果未能解决你的问题,请参考以下文章

Android - 在 CoordinatorLayout 中使用时页脚滚动到屏幕外

表视图单元格仅在屏幕外时自动布局

android文字横向滚动的自定义view

RecyclerView 自动滚动到 WebView/Fresco SimpleDraweeView 项

当虚拟键盘出现在本机反应中时如何自动向上滚动屏幕(在android上)

Android下拉刷新滚动到底部自动加载更多RecyclerView组件