在Fragment中显示确认对话框

l33*_*33t 6 android android-fragments android-fragmentactivity

我正在将我的Android应用程序转换为使用片段.以前,我有一个活动,现在是一个片段.因此,不能再使用此代码:

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

Fragment对象内部,我需要显示一个确认对话框,确认后会将我返回到对象以进行状态更新.

例如

  1. 里面片段X.
  2. 显示确认对话框.
  3. 如果"是"更新X的UI.

我怎么能做到这一点?请提供工作示例代码.

Yuv*_*oid 9

您可以使用如下所示的代码创建对话框(AlertDialog):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();
Run Code Online (Sandbox Code Playgroud)

如果您需要使用不立即关闭对话框的按钮创建对话框,您可以在此处看到我的答案:如何在单击按钮时阻止对话框关闭