首页 > 解决方案 > CoordinatorLayout 中的 RecyclerView 在数据更改时滚动到顶部

问题描述

我在 CoordinatorLayout 内部的 Viewpager 中有一个 RecyclerView,我试图用一个顶部栏进行无休止的滚动,它滚动到顶部并消失,只留下 RecyclerView。滚动效果很好,但是每当我更新 RecyclerView 本身的数据时(甚至像 一样简单notifyItemChanged),RecyclerView 都会滚动到自身的顶部。AppBarLayout 保持隐藏状态,因此只有 RecyclerView 的状态在变化。这是布局本身:

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants"
    android:background="@color/main_bg_color">


    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_layout"
        android:layout_width="match_parent"
        android:background="@color/main_bg_color"
        android:layout_height="wrap_content"
        android:elevation="0dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <LinearLayout
            android:id="@+id/linearLayoutHeader"
            android:layout_width="match_parent"
            app:layout_scrollFlags="scroll"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <include
                android:id="@+id/includedLayout"
                layout="@layout/fragment_profile_before_viewpager" />

            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabIconTint="@color/pink" />
        </LinearLayout>

    </com.google.android.material.appbar.AppBarLayout>


    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

以及viewpager项目的布局(只是一个recyclerview):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/gridRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>

当第一个数据到达时,我调用notifyItemRangeInserted(0, newList.size())适配器。当新数据到达时,我调用notifyItemRangeInserted(oldListSize + 1, newList.size());. 然而,似乎没有任何帮助。我努力了:

标签: androidandroid-layoutandroid-recyclerviewstateandroid-coordinatorlayout

解决方案


推荐阅读