使用自定义的 BottomSheetDialog 类意味着我无法触摸外部来取消



所以我做了一个自定义类,除了样板代码和自定义回调之外,它基本上什么都不做。无论出于何种原因,当我触摸底部表的范围之外时,我似乎无法取消它。

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(true(;
bottomSheetDialog.setCanceledOnTouchOutside(true(;
覆盖调度触摸事件,但我无法让矩形等于整个屏幕大小以外的任何东西。
如果我不使用自定义类(即简单地将我的 CustomBottomSheetDialog 调用更改为仅 BottomSheetDialog(,我会在外面触摸时获得取消,但是当我拖动以隐藏对话框时,我没有得到取消,我需要有。

终于明白了。在 onCreate 中,我添加了一行代码来查找touch_outside视图,并添加了一个单击侦听器以取消对话框。默认情况下会生成touch_outside视图。我不需要将其添加到底表的 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);
}

感谢本教程。

最新更新