BottomSheetBehavior嵌套viewpager其中一个不能滑动的问题

326 阅读1分钟

查看BottomSheetBehavior源码发现在onLayoutChild中初始化nestedScrollingChildRef 会调用

@Nullable  
@VisibleForTesting  
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;  
}

此方法遍历递归如果找到ViewCompat.isNestedScrollingEnabled(view)就直接返回了。所以解决问题就是每次只保证当前viewpager显示的是isNestedScrollingEnabled另外一个不是就行了

方案

viewpager.addOnPageChangeListener(object : SimpleOnPageChangeListener() {  
  
    override fun onPageSelected(position: Int) {  
        if (viewpager.childCount == 0) return  
        zanFragment?.mViewBinding?.rvList?.isNestedScrollingEnabled = (position == 0)  
        commentFragment?.mViewBinding?.rvList?.isNestedScrollingEnabled = (position == 1)  
        bottomSheetBehavior?.onLayoutChild(coordinator, bottomView, ViewCompat.LAYOUT_DIRECTION_RTL)  
    }  
})