多个OK/Cancel对话框,如何在onClick()中确定是哪一个对话框?

4

我创建了一个通用的OkCancelDialog类,通过静态方法方便地在我的应用程序中调用:

  static public void Prompt(String title, String message) {
    OkCancelDialog okcancelDialog = new OkCancelDialog();
    okcancelDialog.showAlert(title, message);     
  }

出于各种原因,我需要在活动中使用onClick监听器,因此在活动中我有以下代码:

  public void onClick(DialogInterface v, int buttonId) {
    if (buttonId == DialogInterface.BUTTON_POSITIVE) { // OK button
         // do the OK thing
    }
    else if (buttonId == DialogInterface.BUTTON_NEGATIVE) { // CANCEL button
         // do the Cancel thing
    }
    else {
      // should never happen
    }
  }

这在应用程序中使用单个对话框非常好,但现在我想添加另一个由同一活动处理的确定/取消对话框。据我所知,只能为活动定义一个onClick(),因此我不确定如何实现这一点。
有什么建议或提示吗?

1
你打算同时在屏幕上有多个对话框吗? - FoamyGuy
@Tim 不行,一次只能显示一个对话框。看起来 DialogInterface v 是个线索,但我不太清楚如何使用它来完成这个棘手的事情。 - Eternal Learner
2个回答

6
尝试类似以下代码的写法...
public class MyActivity extends Activity
    implements DialogInterface.OnClickListener {

    // Declare dialogs as Activity members
    AlertDialog dialogX = null;
    AlertDialog dialogY = null;

    ...

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

        if (dialogX != null) {
            if (dialogX.equals(dialog)) {
                // Process result for dialogX
            }
        }

        if (dialogY != null) {
            if (dialogY.equals(dialog)) {
                // Process result for dialogY
            }
        }
    }
}

编辑 这是我创建AlertDialogs的方法...

private void createGuideViewChooserDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Select Guide View")
        .setSingleChoiceItems(guideViewChooserDialogItems, currentGuideView, this)
        .setPositiveButton("OK", this)
        .setNegativeButton("Cancel", this);
    guideViewChooserDialog = builder.create();
    guideViewChooserDialog.show();
}

1
几乎可以工作了。由于AlertDialog与DialogInterface不同,因此“dialogX.equals(dialog)”返回false,我该如何解决?而且强制转换会产生ClassCastException异常。+1,我快要成功了... - Eternal Learner
1
我有一点困惑,因为我在答案中发布的代码几乎是我自己可行代码的复制/粘贴。 AlertDialog 实现了 DialogInterface,这应该意味着它会工作(正如我所说它对我起作用)。 - Squonk
我的也实现了 DialogInterface 接口,如果我不进行强制转换就不会出现 ClassCastException,但 dialogX.equals(dialog) 仍然返回 false。您确定 equals() 对于实现接口有效吗? - Eternal Learner
我已经三次检查了我的代码,试图弄清楚为什么你的代码不能工作。也许是你创建对话框的方式不对。我已经编辑了我的答案,展示了如何构建对话框以允许用户从电视指南的视图中切换。在这种情况下,在我的原始代码示例中,这将是 dialogX。我有另一个由同一 onClick 监听器处理的 AlertDialog,它使用 equals(...) 方法处理它们而没有问题。 - Squonk

1

你有两个选择。1)你可以在对话框本身上设置OnClickListener。2)你可以根据传入的DialogInterface来确定哪个对话框是哪个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接