最近一个需求一个弹窗上需要几个Tab切换,每个Tab中是可以上下滑动的列表,基于这种设计,很容易想到用BottomSheetDialogFragment + ViewPager+Fragment+RecyclerView,老司机上来就是干,发现写完只有第一页列表可以滑动其他页不可滑动,what?发生了什么,先排除自身代码问题,然后带着疑问去Google,主要的原因就是因为BottomSheetBehavior的findScrollingChild方法并没有有关ViewPager 更新查找子元素view的东西,所以它只能拿到一个页面去滑动,那么就需要对BottomSheetBehavior进行修改,这样的话就需要自己定义BottomSheetDialog:
方法1:
private View findScrollingChild(View view) {
if (view instanceof NestedScrollingChild) {
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;
}
修改后:
@VisibleForTesting
View findScrollingChild(View view) {
if (ViewCompat.isNestedScrollingEnabled(view)) {
return view;
}
if (view instanceof ViewPager) {
ViewPager viewPager = (ViewPager) view;
View currentViewPagerChild = viewPager.getChildAt(viewPager.getCurrentItem());
// View currentViewPagerChild = ViewPagerUtils.getCurrentView(viewPager);
if (currentViewPagerChild == null) {
return null;
}
View scrollingChild = findScrollingChild(currentViewPagerChild);
if (scrollingChild != null) {
return scrollingChild;
}
} else 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;
}
方法2.注意:这种处理方法比较麻烦,换个思维,既然定位到是ViewPager滑动问题,现在Google不是有ViewPager2了嘛,而且ViewPager2底层是用 RecycleView 实现,应该是可以解决这个问题,不出所料,ViewPager2底确解决了这个问题 代码分享下:
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/rl_root_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"

本文档详细记录了解决在BottomSheetDialogFragment中使用ViewPager时,只有第一个页面可滑动的问题。作者首先分析了问题的原因,即BottomSheetBehavior的findScrollingChild方法未处理ViewPager的情况。然后提供了两种解决方案:一是自定义BottomSheetBehavior,修改findScrollingChild方法以支持ViewPager;二是使用ViewPager2,由于其底层基于RecyclerView,能够避免此问题。文章还给出了具体的Java代码实现。
最低0.47元/天 解锁文章
883

被折叠的 条评论
为什么被折叠?



