2014-05-16 29 views
0

我在我的代碼中使用2個alertdialogs,並且我正在嘗試處理Onclick。據我所知,我們只能使用一個Onclick作爲多個alertdialogs,但我不知道如何實現它。 這是我創造我的兩個Alertdialogers多個Alertdialog在一個Onclick

AlertDialog.Builder builder = new Builder(this); 
     builder.setTitle("Attention!"); 
     builder.setMessage("Sorry, location is not determined. Please enable location providers"); 
     builder.setPositiveButton("OK", this); 
     builder.setNeutralButton("Cancel", this); 
     builder.create().show(); 

同樣想爲我的第二Alertbuilder。

+0

我沒有創建Alertdialogs的問題。我的問題是如何實現兩個或更多Alertdialogs只有一個Onclick? – choco

+1

您需要有一個變量來確定您已經膨脹了哪個警報,從而確定您正在點擊哪個警報的按鈕。 – zgc7009

回答

1

你可以做這樣的事情

private static final int ALERT_ONE = 1; 
private static final int ALERT_TWO = 2; 
private int currAlert; 

然後,當你要表現出你的警報

// For alert one 
currAlert = ALERT_ONE; 
AlertDialog.Builder builder = new Builder(this); 
    builder.setTitle("Alert 1!"); 
    builder.setMessage("This is my first alert"); 
    builder.setPositiveButton("OK", this); 
    builder.setNeutralButton("Cancel", this); 
    builder.create().show(); 

或者

// For alert two 
currAlert = ALERT_TWO; 
AlertDialog.Builder builder = new Builder(this); 
    builder.setTitle("Alert 2!"); 
    builder.setMessage("This is my second alert"); 
    builder.setPositiveButton("OK", this); 
    builder.setNeutralButton("Cancel", this); 
    builder.create().show(); 
在你的onClick方法

然後就去做

switch(currAlert){ 
    case ALERT_ONE: 
      //do stuff 
      break; 
    case ALERT_TWO: 
      //do stuff 
      break; 
} 
+0

非常簡單的解決方案,效果很好。非常感謝 – choco

1
AlertDialog.Builder builder = new Builder(this); 
    builder.setTitle("Attention!"); 
    builder.setMessage("Sorry, location is not determined. Please enable location providers"); 
    builder.setPositiveButton("OK", new OnClickListener() 
    { 
     @Override 
     public void onClick(View view) 
     { 
      //do whatever 
     } 
    }); 
    builder.setNeutralButton("Cancel", this); 
    builder.create().show();