2015-09-13 51 views
0

我想做一個警報對話框,但下面的代碼「setNegativeButton」和「setPositiveButton」變成紅色,那意味着有一些錯誤, 我該怎麼辦? 謝謝!AlertDialog錯誤「PositiveButton」

`enter code here`AlertDialog alertDialog = new AlertDialog.Builder(GameActivity.this).create(); 
      alertDialog.setTitle("Game Over!"); 
      alertDialog.setMessage(" Total time " + String.valueOf(timeSpent)); 
      alertDialog.setPositiveButton("Exit", new DialogInterface.OnClickListener() { 

       @Override 
       public void onClick(DialogInterface dialog, int which) { 

       } 

      }); 
      alertDialog.setNegativeButton("Restart", new DialogInterface.OnClickListener() { 

       @Override 
       public void onClick(DialogInterface dialog, int which) { 

       } 

      }); 
      alertDialog.show(); 
+0

請還發布錯誤消息 –

回答

1

您必須setPositiveButton不在AlertDialog中,而是在AllertDialog.Builder()中。

AlertDialog alertDialog = new AlertDialog.Builder(GameActivity.this) 
     .setTitle("Game Over!") 
     .setMessage(" Total time " + String.valueOf(timeSpent)) 
     .setPositiveButton("Exit", new DialogInterface.OnClickListener() { 

      @Override 
      public void onClick(DialogInterface dialog, int which) { 

      } 

     }) 
     .setNegativeButton("Restart", new DialogInterface.OnClickListener() { 

      @Override 
      public void onClick(DialogInterface dialog, int which) { 

      } 

     }) 
     .create(); 

alertDialog.show(); 
0

這樣來做:

AlertDialog alertDialog = new AlertDialog.Builder(GameActivity.this).create(); 
    alertDialog.setTitle("Game Over!"); 
    alertDialog.setMessage(" Total time " + String.valueOf(timeSpent)); 
    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE,"Exit", new DialogInterface.OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 

     } 

    }); 
    alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Restart", new DialogInterface.OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 

     } 

    }); 
    alertDialog.show(); 
0

或者這樣說:

AlertDialog.Builder ad = new AlertDialog.Builder(this); 
    ad.setTitle("TITLE"); 
    ad.setCancelable(true); 
    ad.setMessage("MESSAGE"); 
    ad.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener(){ 
     public void onClick(DialogInterface dialog, int which) { 

     } }); 



    ad.show(); 
相關問題