Reputation: 12656
I want to know when the user presses the back button while my app is displaying a DialogFragment. Activity.onBackPressed() is only called if there is no DialogFragment. When the DialogFragment is open, pressing back closes the dialog but doesn't call onBackPressed(). I need to hook into this event because I need to close the dialog AND the Activity.
Hooking into DialogFragment.onDismiss() isn't good enough because it's called no matter how the dialog is dismissed. I only want to close the Activity when the user presses back.
Thanks in advance...
Upvotes: 1
Views: 1037
Reputation: 3346
You can override dialog fragment's onDetach method();
public void Detach() {
getActivity.finish();
super.detach();
}
or you can call a method from activity like
((MyActivity)getActivity()).myMethod();
Upvotes: 0
Reputation: 2377
You could attach a key listener to the Dialog that your DialogFragment uses to display its content. To do get access to the Dialog, override onCreateDialog in your DialogFragment:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new Handler().post(new Runnable() {
@Override
public void run() {
getActivity().finish();
}
});
}
return false;
}
});
return dialog;
}
I'm not sure you need to wrap the call to finish inside the Runnable. It just seems a bit risky to finish the activity before the dialog has a chance to be dismissed. By posting the Runnable, you are allowing the key to be processed normally, letting Android close the dialog, and then after that your posted Runnable will run to finish the activity too.
Upvotes: 3