【问题标题】:Multiple OK/Cancel dialogs, how to tell, in onClick(), which dialog?多个确定/取消对话框,如何在 onClick() 中判断哪个对话框?
【发布时间】:2012-05-19 06:33:16
【问题描述】:

我创建了一个通用的 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(),所以我不知道如何实现这一点。

有什么建议或提示吗?

【问题讨论】:

  • 你要在屏幕上同时显示多个对话框吗?
  • @Tim No. 一次只有一个对话。看起来DialogInterface v 是一个线索,但我真的不知道如何使用它来完成这个棘手的事情。

标签: android android-dialog


【解决方案1】:

试试这样的...

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();
}

【讨论】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-03
    • 2014-11-26
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多