使用自定义 BottomSheetDialog class 意味着我无法通过 touchOutside 来取消

Using a custom BottomSheetDialog class means I can't touchOutside to cancel

所以我做了一个自定义 class,除了样板代码和自定义回调之外,它基本上什么都不做。无论出于何种原因,当我触摸底部 sheet.

的边界时,我似乎无法取消它
public class CustomBottomSheetDialog extends AppCompatDialog {

public CustomBottomSheetDialog(Context context) {
    super(context, R.style.Theme_Design_Light_BottomSheetDialog);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

@Override
public void setContentView(View view) {
    final CoordinatorLayout coordinator = (CoordinatorLayout) View.inflate(getContext(),
            R.layout.design_bottom_sheet_dialog, null);
    FrameLayout bottomSheet = (FrameLayout) coordinator.findViewById(R.id.design_bottom_sheet);
    BottomSheetBehavior.from(bottomSheet).setBottomSheetCallback(mBottomSheetCallback);
    bottomSheet.addView(view);
    super.setContentView(coordinator);
}

private BottomSheetBehavior.BottomSheetCallback mBottomSheetCallback = new BottomSheetBehavior.BottomSheetCallback() {
    @Override
    public void onStateChanged(View bottomSheet, int newState) {
        if (newState == BottomSheetBehavior.STATE_HIDDEN) {
            cancel(); // The only not boilerplate code here, woo
        }
    }

    @Override
    public void onSlide(View bottomSheet, float slideOffset) { }
};

我尝试过的事情:

bottomSheetDialog.setCancelable(真);
bottomSheetDialog.setCanceledOnTouchOutside(真);
重写 dispatchTouchEvent,但除了整个屏幕的大小之外,我无法让矩形等于任何值。
如果我不使用自定义 class(即只需将我的 CustomBottomSheetDialog 调用更改为 BottomSheetDialog),我会在外部触摸时取消,但是当我拖动以隐藏对话框时我不会取消,这是我必须拥有的。

终于明白了。在 onCreate 中,我添加了一行代码来查找 touch_outside 视图并添加了一个单击侦听器以取消对话框。 touch_outside 视图是默认生成的。我不需要将它添加到底部 sheet 的 XML.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    findViewById(R.id.touch_outside).setOnClickListener(v -> cancel()); // <--- this guy
    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

感谢 this tutorial