2011-05-10 25 views
3

我想用兩個按鈕'YES'和'NO'創建一個DialogAlert。我想要在布爾變量中捕獲對話框的結果。假設用戶點擊'YES'按鈕,那麼DialogResult應該返回一個真值,如果用戶點擊'NO'按鈕,那麼DialogResult應該返回一個False值。請幫我解決這個問題。提前致謝。如何在android中獲得DialogResult?

回答

3

試試這個代碼

boolean result; 
AlertDialog.Builder invalid_input_dialog = new AlertDialog.Builder(Select_party_foods1.this); 
      invalid_input_dialog.setTitle("Event Organise") 
      .setMessage(dialog_message) 
      .setCancelable(true) 
      .setPositiveButton("Ok", new DialogInterface.OnClickListener(){ 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
       result=true; 
       System.out.println("The result is "+result); 
       } 
      }) 
      .setNegativeButton("No", new DialogInterface.OnClickListener(){ 

      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       // TODO Auto-generated method stub 
       result=false; 
       System.out.println("The result is "+result);       
      } 

      }) 
      .show(); 
+0

嗨Jaydeep!其實我想在這個方法之外得到這個變量。我在main方法中調用ShowAlert(「Message」),並且我希望ShowAlert(「Message」)根據所選按鈕返回布爾結果。 – Prachi 2011-05-10 10:03:14

4

我會用一個AlertDialog(see documentation here)。如果你有自己的班級DialogResult的代碼可能看起來像這樣:

DialogResult result = new DialogResult(); 
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) { 
      // User clicked Yes: set the value to your result class here. E.g: 
      MyActivity.result.setValue(true); 
     } 
    }) 
    .setNegativeButton("No", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int id) { 
      // User clicked No: set the value to your result class here. E.g: 
      MyActivity.result.setValue(false); 
     } 
    }); 
AlertDialog alert = builder.create(); 
+0

我試着實現這個代碼,但它給出了一個錯誤,「無法解析DialogResult類」。 – Prachi 2011-05-10 10:08:07

+1

我假設你的問題是你有一個叫做DialogResult的類... – Kristian 2011-05-10 14:02:01