2012-03-18 38 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();