Disable dragging of BottomSheetDialogFragment with scrollable children

生来就可爱ヽ(ⅴ<●) 提交于 2020-08-22 05:06:19

问题


Is it possible to disable dragging for a BottomSheetDialogFragment, containing scrollable views such as a ViewPager or a NestedScrollView, such that it can't be dragged neither up nor down but still be dismissed by touching outside and that the children can be dragged anyways?

I've looked at all the answers here but I am not pleased since most don't take into account scrollable children or work by forcing the expanded state. The closest is this answer but nonetheless allows dragging the sheet up.

Is there any solution or at least guidance at what should I modify of the original source code?


回答1:


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.



来源:https://stackoverflow.com/questions/48360305/disable-dragging-of-bottomsheetdialogfragment-with-scrollable-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!