2012-03-18 74 views
5

我正在将我的Android应用程序转换为使用片段。以前,我有一个活动现在是一个片段。因此,该代码可以不再使用:在片段中显示确认对话框

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

Fragment对象中,我需要显示一个确认对话框,确认抛出我回到了状态更新的对象之后。

E.g.

  1. 内部片段X.
  2. 显示确认对话框。
  3. 如果 “是” 为X.

更新UI我怎样才能做到这一点?请提供工作示例代码。

回答

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(); 

如果你需要创建一个按钮,对话框不立即关闭该对话框本身,你可以在这里看到我的回答:How to prevent a dialog from closing when a button is clicked

+0

谢谢。这就够了! (但我怀疑最好的解决方案是使用'DialogFragment'并以某种方式将结果传播回原始片段。) – l33t 2012-03-18 22:03:50

0
  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();