问题
I need to handle the end of a DialogFragment (after a call to .dismiss) - for example, I would show a toast inside the activity that "contains" the fragment after dismiss.
How do I handle the event?
回答1:
Override onDismiss()
in your DialogFragment, or use setOnDismissListener()
in the code block where you are building the fragment.
回答2:
I faced similar problem, but I wanted to inform another activity about the dialog dismiss (not the activity that created and showed the dialog).
Although you can just override the onDismiss()
method in your DialogFragment as Austyn Mahoney suggested, yet you can NOT use setOnDismissListener()
, because DialogFragment simply does not provide such method (according to: Android Developers DialogFragment Reference).
But still there is another nice way to inform any other activity about the dialog dismiss, (I've found it there: DialogFragment and onDismiss), here it comes:
Firstly you should make your Activity (the one that you want to pass information about dialog dismiss) implement OnDismissListener
:
public final class YourActivity extends Activity implements DialogInterface.OnDismissListener {
@Override
public void onDismiss(final DialogInterface dialog) {
//Fragment dialog had been dismissed
}
}
Again according to Android Developers DialogFragment Reference DialogFragment already implements OnDismissListener
with onDismiss()
method. That's why you should override it and call there your onDismiss()
method which you implemented in YourActivity:
public final class DialogFragmentImage extends DialogFragment {
@Override
public void onDismiss(final DialogInterface dialog) {
super.onDismiss(dialog);
final Activity activity = getActivity();
if (activity instanceof DialogInterface.OnDismissListener) {
((DialogInterface.OnDismissListener) activity).onDismiss(dialog);
}
}
}
来源:https://stackoverflow.com/questions/15163520/dialogfragment-close-event