我如何监听BottomSheetDialogFragment
的最终关闭?我只想在最终关闭时保存用户更改...
我尝试了以下方法:
方法1
这只有在通过向下滑动对话框关闭时才会触发(不是在返回按键或点击外部触摸时)
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Dialog d = super.onCreateDialog(savedInstanceState);
d.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
BottomSheetDialog d = (BottomSheetDialog) dialog;
FrameLayout bottomSheet = (FrameLayout) dialog.findViewById(android.support.design.R.id.design_bottom_sheet);
BottomSheetBehavior behaviour = BottomSheetBehavior.from(bottomSheet);
behaviour.setState(BottomSheetBehavior.STATE_EXPANDED);
behaviour.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_HIDDEN)
{
// Bottom Sheet was dismissed by user! But this is only fired, if dialog is swiped down! Not if touch outside dismissed the dialog or the back button
Toast.makeText(MainApp.get(), "HIDDEN", Toast.LENGTH_SHORT).show();
dismiss();
}
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
}
});
}
});
return d;
}
方法二
这个方法无法区分最终的解雇和来自屏幕旋转或活动重新创建的解雇...
@Override
public void onDismiss(DialogInterface dialog)
{
super.onDismiss(dialog);
// this works fine but fires one time too often for my use case, it fires on screen rotation as well, although this is a temporarily dismiss only
Toast.makeText(MainApp.get(), "DISMISSED", Toast.LENGTH_SHORT).show();
}
问题
我该如何监听表示用户已完成对话框的事件?
onCancel()
的使用。警告!如果您禁用了BottomSheet的取消功能(参见https://dev59.com/8VgQ5IYBdhLWcg3w1nVA),那么这个解决方案和类似的解决方案将无效。如果您设置了`bottomSheetDialogFragment.setCancelable(false);`,监听器将不会被调用! - CoolMind