문제

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.

도움이 되었습니까?

해결책

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

다른 팁

         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());       
         builder.setTitle("Your Title");
         builder.setMessage("Your Dialog Message");
         builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int id) {
                  //TODO
                  dialog.dismiss();
             }
         });
         builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int id) {
                  //TODO
                  dialog.dismiss();
             }
         });
         AlertDialog dialog = builder.create();
         dialog.show();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top