Prevent dismissal of BottomSheetDialogFragment on touch outside

痞子三分冷 提交于 2019-11-27 14:39:21

You should use #setCancelable(false) when you create an instance of it.

    BottomSheetDialogFragment bottomSheetDialogFragment = new SequenceControlFragmentBottomSheet();
    bottomSheetDialogFragment.setCancelable(false);
    bottomSheetDialogFragment.show(getChildFragmentManager(), bottomSheetDialogFragment.getTag());

setCancelable(false) will prevent the bottom sheet dismiss on back press also. If we look at the layout resource for the bottom sheet in android design support library, there is a View component with ID touch_outside and there is an OnClickListener set in method wrapInBottomSheet of BottomSheetDialog, which is used for detecting clicks outside and dismiss the dialog. So, to prevent cancel on touch outside the bottom sheet we need to remove the OnClickListener.

Add these line to onActivityCreated method (or any other life cycle method after onCreateView).

@Override public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    View touchOutsideView = getDialog().getWindow()
        .getDecorView()
        .findViewById(android.support.design.R.id.touch_outside);
    touchOutsideView.setOnClickListener(null);
}

Also if you want to prevent the bottom sheet dismiss by swiping down, change the bottom sheet dialog behaviour Hideable false. To setHideable(false) add the following code to the onCreateDialog method.

@Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    final BottomSheetDialog bottomSheetDialog =
        (BottomSheetDialog) super.onCreateDialog(savedInstanceState);

    bottomSheetDialog.setOnShowListener(new DialogInterface.OnShowListener() {
      @Override public void onShow(DialogInterface dialog) {
        FrameLayout bottomSheet =
        bottomSheetDialog.findViewById(android.support.design.R.id.design_bottom_sheet);

        if (null != bottomSheet) {
          BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet);
        behavior.setHideable(false);
        }
      }
    });
    return bottomSheetDialog;
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!