I'd like to make a dialog fragment
that asks "Are you sure?" with a "yes/no" reply.
I've looked at the documentation and it's really verbose, going all over the place, explaining how to make advanced dialog boxes, but no intact code on making a simple 'hello world' kind of dialog box. Most tutorials utilize the deprecated dialog box system. The official blog seems to be unnecessarily complicated and difficult to understand.
So, what's the simplest way to create and display a really basic Alert Dialog? Bonus points if it's using the support library.
Simply create a
DialogFragment
(sdk or support library) and override itsonCreateDialog
method to return anAlertDialog
with the desired text and buttons set on it:To do something when the user uses one of the button you'll have to provide an instance of a
DialogInterface.OnClickListener
instead of thenull
references from my code.For those coding with Kotlin and Anko, you can now do dialogs in 4 lines of code:
A DialogFragment is really just a fragment that wraps a dialog. You can put any kind of dialog in there by creating and returning the dialog in the onCreateDialog() method of the DialogFragment.
Heres an example DialogFragment:
To create the dialog call:
And to dismiss the dialog from somewhere:
All of that code will work perfectly with the support library, by just changing the imports to use the support library classes.
because of Activity / Fragment lifecycle @athor & @lugsprog approach can fail, more elegant way is to **get activity context from method onAttach and store it as weak reference ** (&try to avoid non default constructor in DialogFragment!, to pass any argument to dialog use arguments) like this:
EDIT: & if You wanna dismiss dialog then:
something like this :
EDIT2: & if u wanna set dialog as non cancelable u should change onCreatweDialog return statement like this: