Disable dragging of BottomSheetDialogFragment with scrollable children

后端 未结 1 1391
无人共我
无人共我 2021-02-15 16:03

Is it possible to disable dragging for a BottomSheetDialogFragment, containing scrollable views such as a ViewPager or a NestedScrollView,

相关标签:
1条回答
  • 2021-02-15 17:09

    If you debug your application and use Layout Inspector tool, you will see that BottomSheetDialogFragment uses CoordinatorLayout. Dimmed background is a simple view with an OnClickListener that closes the dialog, and sheet movement is driven by CoordinatorLayout.Behavior.

    This can be overriden by modifying created dialog:

    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;
    }
    

    Kotlin:

    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
    }
    

    This does use internal IDs of design library, but unless for some reason they're changed this should be stable.

    0 讨论(0)
提交回复
热议问题