我遇到了麻烦,我认为是 CoordinatorLayout
的错但不确定。我正在使用 ViewPager2
在 ConstraintLayout
内我使用 CoordinatorLayout
喜欢 BottomSheet
.但是当我拖动隐藏它时效果不佳。我替换了 ViewPager2
通过 ViewPager
它运作良好。我希望你能帮助我。
这是我的 XML 文件:
<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">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/bottom_sheet_behavior"
app:behavior_hideable="false"
app:behavior_peekHeight="60dp" >
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="4:3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="#0000FF"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
最佳答案
这可以通过禁用 ViewPager2
的嵌套滚动来解决。 RecyclerView
;但自从 RecyclerView
无法通过 ViewPager2
直接访问图书馆。那么在布局上就无法实现。
所以,我们可以得到 RecyclerView
使用java反射如下:
java :
public static RecyclerView getRecyclerView(ViewPager2 viewPager) {
try {
Field field = ViewPager2.class.getDeclaredField("mRecyclerView");
field.setAccessible(true);
return (RecyclerView) field.get(viewPager);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
Kotlin :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
}
然后禁用嵌套滚动:java :
RecyclerView recyclerView = getRecyclerView(viewPager);
if (recyclerView != null) {
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER); // Optional
}
Kotlin :val recyclerView = viewPager.getRecyclerView()
recyclerView?.isNestedScrollingEnabled = false
recyclerView?.overScrollMode = View.OVER_SCROLL_NEVER // Optional
这适用于我,无需设置 OverScrollMode
,所以,如果它不工作,你可以禁用 OverScrollMode
像上面一样。
关于android - BottomSheet + ViewPager2 拖动隐藏不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59915600/