解决CoordinatorLayout 嵌套ViewPager2 页面不整体滑动

2,234 阅读1分钟

页面布局

<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:id="@+id/coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/c_ffffff"
        app:layout_behavior=".widget.behavior.AppBarLayoutBehavior"
        app:liftOnScroll="true">

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

    <com.chic.base.widget.recycler.RecyclerView
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />


</androidx.coordinatorlayout.widget.CoordinatorLayout>

描述 :底部RecyclerView 中某个Item 使用了ViewPager2 导致整个 RV 和上部的AppBarLayout 不一起滚动,

原因: ViewPager2使用RecyclerView实现,RecyclerView吃掉了nested的一系列方法,导致无法回传至CoordinatorLayout,导致behavior失效,最终无法滑动

解决办法:禁用RV 的nestedScrollingEnable

private void disallowRvNestedScroll(ViewPager2 viewPager2) {
    for (int i = 0; i < viewPager2.getChildCount(); i++) {
        if (viewPager2.getChildAt(i) instanceof RecyclerView) {
            viewPager2.getChildAt(i).setNestedScrollingEnabled(false);
        }
    }
}