一个Onclick中有多个Alertdialog

时间:2014-05-16 18:53:31

标签: android android-alertdialog

我在我的代码中使用了2个alertdialogs,我正在尝试处理Onclick。据我所知,我们只能使用一个Onclick用于多个alertdialogs,但我不知道如何实现它。 这就是我创建两个Alertdialogers的方式

    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也一样。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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();