OnCancelListener is not called in DialogFragment

前端 未结 5 1385
盖世英雄少女心
盖世英雄少女心 2020-12-30 00:30

I have a simple AlertDialog that displays a list of some items and upon clicking one of them, the clicked item is passed back to the enclosing Activity

5条回答
  •  感动是毒
    2020-12-30 01:04

    It might have to do with the fact that there is no explicit call to cancel() from your code. The OnCancelListener documentation says:

    This will only be called when the dialog is canceled

    Which probably needs an explicit cancel() call.

    Either make a positive/negative button with a OnClickListener that calls DialogInterface#cancel() or use a OnDismissListener() with an extra check to see if a list item was clicked.

    Also, to listen for a back keypress and cancel the dialog, you can set up an OnKeyListener, like outlined in this SO answer

    Also, once you have the Dialog set up, it would also be a good idea to use Dialog#setCanceledOnTouchOutside() in case the the user taps outside the Dialog.

    Edit: The below part is the easy way to handle cancel events in a DialogFragment.

    Since you are using a DialogFragment, this class has a very handy method, DialogFragment#onCancel() which gets called when the DialogFragment is cancelled. Do your logic in there.

    DialogFragments are more complex, with a slightly different lifecycle than normal dialogs. Therefore, first check the documentation if you have a certain Dialog-based approach that you are trying to port to a DialogFragment, some methods may exist that allow your new implementation to function properly!

提交回复
热议问题