禁用带有可滚动子项的BottomSheetDialogFragment的拖动

One*_*ion 4 android bottom-sheet

是否可以禁用对BottomSheetDialogFragment包含可滚动视图(例如a ViewPager或a)的a的NestedScrollView拖动,以使其既不能向上或向下拖动,但仍可以通过触摸外部而关闭,并且无论如何都可以拖动子级?

我在这里查看了所有答案但我不满意,因为大多数人没有考虑可滚动的子项或通过强制展开状态来工作。最接近的是这个答案,但是仍然允许将工作表向上拖动。

在我应修改原始源代码方面,是否有任何解决方案或至少是指南?

Paw*_*wel 15

如果您调试应用程序并使用“布局检查器”工具,则会看到BottomSheetDialogFragment使用CoordinatorLayout。变暗的背景是一个带有的简单视图,它OnClickListener可以关闭对话框,并且图纸移动由来驱动CoordinatorLayout.Behavior

可以通过修改创建的对话框来覆盖它:

Java:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Dialog d = super.onCreateDialog(savedInstanceState);
    // view hierarchy is inflated after dialog is shown
    d.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialogInterface) {
            //this disables outside touch
            d.getWindow().findViewById(R.id.touch_outside).setOnClickListener(null);
            //this prevents dragging behavior
            View content = d.getWindow().findViewById(R.id.design_bottom_sheet);
            ((CoordinatorLayout.LayoutParams) content.getLayoutParams()).setBehavior(null);
        }
    });
    return d;
}
Run Code Online (Sandbox Code Playgroud)

科特林:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    val d = super.onCreateDialog(savedInstanceState)
    //view hierarchy is inflated after dialog is shown
    d.setOnShowListener {
        //this disables outside touch
        d.window.findViewById<View>(R.id.touch_outside).setOnClickListener(null)
        //this prevents dragging behavior
        (d.window.findViewById<View>(R.id.design_bottom_sheet).layoutParams as CoordinatorLayout.LayoutParams).behavior = null
    }
    return d
}
Run Code Online (Sandbox Code Playgroud)

这确实使用了设计库的内部ID,但是除非出于某些原因更改了它,否则它应该是稳定的。

  • 您可以覆盖`R.id.design_bottom_sheet`的更多布局参数以包括gravity bottom和wrap_content的layout_height,但是那时候我开始怀疑您是否应该仅创建具有底部重力的常规DialogFragment并滑动进/出动画因为您不使用工作表的核心功能,即嵌套滚动,拖动和捕捉。 (2认同)