解决BottomSheetDialogFragment + ViewPager2 + RecyclerView嵌套产生的滑动问题

2,261 阅读4分钟

前言

BottomSheetDialogFragment是官方提供的工具,平时用起来很爽,但是在使用过程中也遇到了一些问题,现把遇到的其中一个问题记录下来。

中间是解决问题的过程,可以直接跳转到文章第4部分查看问题解决代码。

1、场景

在开发时遇到一个需求,点击按钮弹出弹窗,弹窗需要跟随滑动展开到全屏状态,或收缩从底部消失,所以第一时间想到了使用BottomSheetDialogFragment实现。DialogFragment中需要包含一个ViewPager2以左右翻页,ViewPager2有三页,每一页都包含一个 Fragment,每个 Fragment 的根 view 是一个的RecyclerView。

2、问题&现象

弹出弹窗后,ViewPager2可以左右滑动,滑动ViewPager2以外的区域可以正常折叠、展开、收起弹窗。滑动RecyclerView区域,RV内部的内容可以正常上下滚动,但是弹窗不会跟随滚动展开至全屏或收起从底部消失。

3、分析

查看源码可以发现BottomSheetDialogFragment内部是通过BottomSheetDialog实现的,所以我们可以简单的将BottomSheetDialogFragment理解为一个披着 Fragment 外衣的 BottomSheetDialog,而 BottomSheetDialog 是一个拥有 BottomSheetBehavior 行为的 Dialog,可以实现从底部弹出和上下拉伸的效果,所以问题的症结可能出在BottomSheetBehavior上面。

BottomSheetBehavior继承自CoordinatorLayout.Behavior,Behavior的主要作用是协调CoordinatorLayout直接child View的交互行为,所以如果想使用Behavior,必须要在CoordinatorLayout的直接子view中使用。我们可以通过BottomSheetDialog的布局文件design_bottom_sheet_dialog验证一下

<FrameLayout
    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/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

  <androidx.coordinatorlayout.widget.CoordinatorLayout
      android:id="@+id/coordinator"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:fitsSystemWindows="true">

    <View
        android:id="@+id/touch_outside"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="false"
        android:importantForAccessibility="no"
        android:soundEffectsEnabled="false"
        tools:ignore="UnusedAttribute"/>

    <FrameLayout
        android:id="@+id/design_bottom_sheet"
        style="?attr/bottomSheetStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|top"
        app:layout_behavior="@string/bottom_sheet_behavior"/>

  </androidx.coordinatorlayout.widget.CoordinatorLayout>

</FrameLayout>

这就是BottomSheetDialog的基础布局,我们自己的View最终会被add到id为design_bottom_sheet的FrameLayout中,该布局指定layout_behavior"@string/bottom_sheet_behavior",其实就是com.google.android.material.bottomsheet.BottomSheetBehavior。也正如上文所说的,design_bottom_sheet是CoordinatorLayout的直接子View。

前面也说过,我们自己的布局是嵌套RecyclerView的,而这里又涉及到了CoordinatorLayout,前者实现了NestedScrollingChild2NestedScrollingChild3接口,后者实现了NestedScrollingParent2接口,这就有了嵌套滑动。

根据对嵌套滑动的了解,RecyclerView在响应滑动事件的同时,也会将事件传递到CoordinatorLayout中,但是CoordinatorLayout本身并没有处理嵌套滑动而是全部给 Behavior 代理,这也就意味着是BottomSheetBehavior对事件的处理逻辑出了问题。对嵌套滑动不了解的朋友可以查看浅析NestedScrolling嵌套滑动机制之基础篇这一系列文章。

我们可以直接看BottomSheetBehavior的onNestedPreScroll()方法,onNestedPreScroll()方法的作用是接收子view处理滑动前的滑动距离信息, 在这里父view可以优先响应滑动操作, 消耗部分或者全部滑动距离。

public void onNestedPreScroll(
      @NonNull CoordinatorLayout coordinatorLayout,
      @NonNull V child,
      @NonNull View target,
      int dx,
      int dy,
      @NonNull int[] consumed,
      int type) {
    
    ...
    
    View scrollingChild = nestedScrollingChildRef != null ? nestedScrollingChildRef.get() : null;
    if (isNestedScrollingCheckEnabled() && target != scrollingChild) {
      return;
    }
        
    ...
    
}

在该方法中有一段判断逻辑代码,如果判断为true则直接返回,不会再继续执行。条件 isNestedScrollingCheckEnabled() 用来管理是否允许嵌套滑动,默认为true。关键条件逻辑是 target != scrollingChild ,即判断是不是同一个View, target是指真正滑动的view,即ViewPage2 item中的RecyclerView,scrollingChild 是通过 nestedScrollingChildRef.get() 获取的,接着看nestedScrollingChildRef。

nestedScrollingChildRef是一个弱引用,在 onLayoutChild() 方法中通过findScrollingChild(child) 赋值,child 是绑定了 BottomSheetBehavior 下的子View 。

WeakReference<View> nestedScrollingChildRef;

@Override
public boolean onLayoutChild(... , @NonNull final V child, ...) {
    ...
    
    nestedScrollingChildRef = new WeakReference<>(findScrollingChild(child));

    ...
}

接着看产生问题的关键方法 findScrollingChild(child) 方法

  View findScrollingChild(View view) {
    if (ViewCompat.isNestedScrollingEnabled(view)) {
      return view;
    }
    if (view instanceof ViewGroup) {
      ViewGroup group = (ViewGroup) view;
      for (int i = 0, count = group.getChildCount(); i < count; i++) {
        View scrollingChild = findScrollingChild(group.getChildAt(i));
        if (scrollingChild != null) {
          return scrollingChild;
        }
      }
    }
    return null;
  }

子 view 传进来后首先会判断是否可嵌套滑动 isNestedScrollingEnabled,可以滑动的话直接返回该子 view,不可滑动继续执行。

接着会判断该 view 是否是 ViewGroup,是的话会循环该 group 下的所有子 view,递归执行 findScrollingChild 直到找到第一个可以嵌套滑动的子view 然后返回,停止递归。没有的话返回null,表示已经遍历所有 view 且不存在可嵌套活动的view 。

所以,从源码中可以看出该方法的作用是找到可嵌套滑动的控件,并且仅获取绑定控件中的一个可滑动的控件(view) ,多的话就取第一个。

我们都知道 ViewPager2 滑动是借助 RecyclerViewImpl 实现的,RecyclerViewImpl继承自RecyclerView,具有嵌套滑动的效果,那么按照源码逻辑得到的nestedScrollingChildRef 就是ViewPager2下的 RecyclerViewImpl

回到前面的onNestedPreScroll()方法,scrollingChild 也就成了 RecyclerViewImpl,target自然也就不等于scrollingChild,从而导致BottomSheetBehavior不会同步滑动。

而我们希望获取的可滑动 view 是内部的 RecyclerView。

这么一来,我们只需要设置 ViewPager2 的 isNestedScrollingEnabled 为 false ,也就是禁用嵌套滑动,就可以继续向下递归,找到内部的 RecyclerView。

这里如果直接给 ViewPager2 设置 android:nestedScrollingEnabled="false"是没有效果的,原因前面说过,我们需要禁用的是 ViewPager2 中的 RecyclerView 的嵌套滑动。

ViewPager2 的 RecyclerView 默认是不可访问的,这里我们可以使用反射获取 RecyclerView 然后禁用滑动。

//获取RecyclerView
fun ViewPager2.getRecyclerView(): RecyclerView? {
    try {
        val field = ViewPager2::class.java.getDeclaredField("mRecyclerView")
        field.isAccessible = true
        return field.get(this) as RecyclerView
    } catch (e: NoSuchFieldException) {
        e.printStackTrace()
    } catch (e: IllegalAccessException) {
        e.printStackTrace()
    }
    return null
}

//禁用滑动
val recyclerView = viewPager.getRecyclerView()
recyclerView?.isNestedScrollingEnabled = false
recyclerView?.overScrollMode = View.OVER_SCROLL_NEVER // Optional

反射毕竟不是一种特别好的方法,这里有一种更好的方式设置。

viewPager2.children.find { it is RecyclerView }?.let {
    (it as RecyclerView).isNestedScrollingEnabled = false
}

如果还不生效可以关闭 RecyclerView的滑动模式。

recyclerView?.overScrollMode = View.OVER_SCROLL_NEVER

运行之后会发现 DialogFrament 可以随着 RecyclerView滑动而展开、收缩。

但随之而来一个新问题,只有第一页的RV可以滑动正常,后面的几页的RV滑动仍然有问题。

这是因为nestedScrollingChildRef已经通过findScrollingChild获取到可滑动页面,也就是 ViewPager2 第一页中的 RecyclerView,但是由于翻页后 nestedScrollingChildRef 并没有改变,后面的几页也就不可能正常滑动。

所以我们只需要在每次翻页后刷新 nestedScrollingChildRef 的值即可,代码思路如下。

public void invalidateScrollingChild(View scrollingChildView) {
    mNestedScrollingChildRef = new WeakReference<>(scrollingChildView);
}

继承 BottomSheetBehavior 加入刷新的逻辑,然后在翻页的时候调用即可。

如果不想通过继承的方式刷新数据,还有一种简单的方法。

继续看源码,会发现 nestedScrollingChildRef 是在 onLayoutChild 方法中被赋值的,onLayoutChild 方法重写自 CoordinatorLayout,在 CoordinatorLayout 的 onLayout 方法中被调用。到这里就很清晰了,我们只需要在翻页后调用根View的 requestLayout() 更新view,更新view会调用 onLayout 方法,自然就可以达到更新参数的目的了。

完整代码如下

4、解决方案

在继承了BottomSheetDialogFragment的类中添加调用如下代码。

    // 设置dialog下的view是否可滑动
    private fun setNestedScrollEnable() {
        viewPager2.apply {
            children.find { it is RecyclerView }?.let {
                (it as RecyclerView).apply {
                    isNestedScrollingEnabled = false
                    overScrollMode = View.OVER_SCROLL_NEVER
                }
            }
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    setPageViewNestedScrollEnable(position)
                    dialog?.findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet)?.requestLayout()
                }
            })
        }
    }

    //设置当前显示的view可嵌套滑动,其余页面禁止
    private fun setPageViewNestedScrollEnable(currentPosition: Int) {
        for (position in 0..currentPosition) {
            val view = (viewPager2.getChildAt(0) as RecyclerView).layoutManager?.findViewByPosition(position)
            if (view != null) {
                findFirstScrollChild(view, position == currentPosition)
            }
        }
    }

    private fun findFirstScrollChild(view: View, isCurrentView: Boolean) {
        if (view is ViewGroup) {
            if (view is RecyclerView) {
                view.isNestedScrollingEnabled = isCurrentView
                return
            }
            for (childView in view) {
                findFirstScrollChild(childView, isCurrentView)
            }
        }
    }

5、总结

其实解决思路很简单,将BottomSheetBehavior中需要响应嵌套滑动的子 View 的isNestedScrollingEnabled 设置为 true,其余子 View的 isNestedScrollingEnabled 设为 false。然后在ViewPager2切换页面的时候,触发CoordinatorLayout.requestLayout()修改nestedScrollingChildRef值即可。