2012-10-10 116 views
0

爲什麼編譯器在下面的代碼中顯示setPositiveButton和setNegativeButton的錯誤。如果我使用setButton,則沒有錯誤,但只允許我在警報對話框上顯示一個按鈕。我想要2個按鈕。根據許多教程,必須使用setPositiveButton和setNegativeButton設置兩個按鈕的提示對話框。爲什麼會爲這些編譯錯誤?警報對話,如何讓兩個按鈕都出現

public void onClick(View v) { 

     AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create(); 
     alert.setTitle("Confirm Edit"); 
     alert.setMessage("do you want to save edits?"); 

     alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { 

      public void onClick(DialogInterface dialog, int which) { 
      // launches other activity if the user presses the OK button 
       Intent myIntent = new Intent(MainActivity.this, TestScreen.class); 
      MainActivity.this.startActivity(myIntent); 

      Toast.makeText(MainActivity.this, "Edits saved", Toast.LENGTH_SHORT).show(); 

      } 
     }); 

     alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

      public void onClick(DialogInterface dialog, int which) { 
       Toast.makeText(MainActivity.this, "Edits Canceled", Toast.LENGTH_SHORT).show(); 
       dialog.cancel(); 
      } 
     }); 
     alert.show(); 


    } 
}); 

回答

0

你的代碼是正確的,只有你需要改變一點點。使用Builder類創建AlertDialog。

Builder builder = new AlertDialog.Builder (MainActivity.this); 
builder.setTitle ("Confirm Edit"); 
builder.setMessage("do you want to save edits?"); 

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 

      public void onClick(DialogInterface dialog, int which) { 
      // launches other activity if the user presses the OK button 
       Intent myIntent = new Intent(MainActivity.this, TestScreen.class); 
      MainActivity.this.startActivity(myIntent); 

      Toast.makeText(MainActivity.this, "Edits saved", Toast.LENGTH_SHORT).show(); 

      } 
     }); 

     builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

      public void onClick(DialogInterface dialog, int which) { 
       Toast.makeText(MainActivity.this, "Edits Canceled", Toast.LENGTH_SHORT).show(); 
       dialog.cancel(); 
      } 
     }); 


// Now finally showing Alert Dialog. 
AlertDialog alert = builder.create(); 
alert.show(); 
+0

謝謝。它現在有效 – Kevik