Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show confirmation dialog in Fragment

I'm converting my Android application to use fragments. Previously, I had an activity that is now a fragment. Hence, this code can no longer be used:

showDialog(CONFIRM_ID);
// ...
@Override
public Dialog onCreateDialog(int id) {
    // Create the confirmation dialog...
}

From within the Fragment object, I need to show a confirmation dialog that after confirmation throws me back to the object for status update.

E.g.

  1. Inside fragment X.
  2. Show confirmation dialog.
  3. If "yes" update UI for X.

How can I accomplish this? Please provide working sample code.

like image 905
l33t Avatar asked Mar 18 '12 21:03

l33t


1 Answers

You can simply create your dialogs (AlertDialog) using the code as shown here: http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
       .setCancelable(false)
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                MyActivity.this.finish();
           }
       })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       });
AlertDialog alert = builder.create();
alert.show();

If you need to create dialogs with buttons that do not immediately dismiss the dialog itself you can see my answer here: How to prevent a dialog from closing when a button is clicked

like image 168
YuviDroid Avatar answered Oct 01 '22 01:10

YuviDroid