Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel or dismiss a custom dialog in its onCreate method?

I have created a custom dialog called MyCustomDialog which extends Dialog. I create and show my custom dialog as follows:

new MyCustomDialog(myContext).show();

I override the Dialog.onCreate(Bundle savedInstanceState) method to do my initialisation. I also check in this method whether a certain condition holds and, if not, I would like to dismiss/cancel my dialog. I have tried calling the cancel() and dismiss() methods in my dialog's onCreate(Bundle savedInstanceState) and onStart() methods but it has no effect.

Anyone know how to cancel or dismiss a dialog (from within the dialog) before it shows?

like image 868
Adil Hussain Avatar asked Jul 31 '12 16:07

Adil Hussain


People also ask

How do I dismiss custom dialog?

By calling setCancelable(boolean) and setCanceledOnTouchOutside(boolean) we can set whether this dialog is cancelable with the BACK key, and whether this dialog is canceled when touched outside the window's bounds. We also implement OnCancelListener and OnDismissListener to handle the cancel and dismiss events.

How to close DialogFragment?

tl;dr: The correct way to close a DialogFragment is to use dismiss() directly on the DialogFragment. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog. Dismiss the fragment and its dialog.

How do you dismiss dialog with click on outside of dialog?

You can use dialog. setCanceledOnTouchOutside(true); which will close the dialog if you touch outside of the dialog.

What is DialogFragment in android?

Android DialogFragments. DialogFragment is a utility class which extends the Fragment class. It is a part of the v4 support library and is used to display an overlay modal window within an activity that floats on top of the rest of the content. Essentially a DialogFragment displays a Dialog but inside a Fragment.


1 Answers

You should place the logic to determine if the dialog is to be shown outside of the onCreate() method. it does not belong there.

Alternatively, rename your show() method showIfRequired() (or something), and add the conditional show logic there.

I know this doesn't technically answer your question, but what you are trying to do is not the correct design. That's a good thing, as doing in the right way is actually simpler.

Also, as a side note, you should using DialogFragment in favor of Dialog. it's available in the v4 support library.

like image 120
Jeffrey Blattman Avatar answered Nov 10 '22 04:11

Jeffrey Blattman