Issue
So I'm trying to call a dialogFragment, it works perfectly until I call the onDismiss function from the activity to make an action...
I got a dialog fragment in the hangman game which says if you won or loose, there is a button in the dialog which says if "try again" or "next word", in case you won or loose, it looks like this:
When the client clicks one of these buttons the dialog will disappear and a new word should appear and reset everything except the word if won... So I've tried to set onDismiss listener to the dialogFragment inside the activity where the current game is running, but instead of setting dismiss listener, the app crashes with this error:
java.lang.IllegalStateException: Fragment already added: WonDialogFragment{db6bbec}
here is the code where I call the dialogFragment:
// in case the user won
if (isWon) {
// Disable all the buttons immediately.
setEnabledToEachButton(false);
// check if there is already a dialog.
if (!dialogFragment.isAdded() && !dialogFragment.isVisible()) {
// show the dialog
dialogFragment.show(getSupportFragmentManager(), WonDialogFragment.WON_TAG);
dialogFragment.onDismiss(new DialogInterface() {
@Override
public void cancel() {
}
@Override
public void dismiss() {
currentIndex++;
nextWordOrTryAgain();
updateTextView();
}
});
}
}
if I should provide more information to solve my problem let me know... thank you for your time.
Solution
onDismiss is a lifecycle method of DialogFragment. You are not supposed to call it.
You have 2 options,
Try to use the OnDismissListener:
dialogFragment.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
currentIndex++;
nextWordOrTryAgain();
updateTextView();
}
}
Or to Create a custom listener interface:
public interface DialogDismissed {
void onDialogDismissed();
}
Inside you dialog, have a setter and keep the listener interface:
public void setListener(DialogDismissed listener) {
mListener = listener;
}
When you call dismiss() inside you dialog use:
if (mListener != null) {
mListener.onDialogDismissed()
}
And when creating the Dialog, set the listener:
dialogFragment.setListener(new DialogDismissed {
@Override
void onDialogDismissed() {
currentIndex++;
nextWordOrTryAgain();
updateTextView();
}
});
Answered By - gioravered
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.