所以我创建了一个自定义类,除了样板代码和自定义回调之外什么都没做。无论出于何种原因,当我触摸到底页的边界之外时,我似乎无法取消它。
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,但除了整个屏幕的大小外,我无法使矩形等于任何东西。
如果我不使用自定义类(即只是将我的CustomBottomSheetDialog调用更改为BottomSheetDialog),我会在外面触摸取消,但是当我拖动隐藏对话框时我没有取消,这是我必须拥有的。
答案 0 :(得分:0)
终于明白了。在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);
}