在确认对话框中单击了哪个按钮

时间:2016-07-09 15:40:05

标签: android dialog

我有一个问题是得到"结果"自定义确认对话框 我构建了以下类:

public class MessageDialog {
  private static int result;

  public static final int OK = 0;
  public static final int CANCEL = 1;

  public static int showConfirmDialog(Context context, String message) {
    result = OK;

    AlertDialog.Builder ad = new AlertDialog.Builder(context);
    ad.setCancelable(false);
    ad.setMessage(message);
    ad.setTitle("Confirm");
    ad.setPositiveButton("Yes", new ButtonPressedListener());
    ad.setNegativeButton("No", new ButtonPressedListener());
    ad.create().show();

    return result;
  }

  private static class ButtonPressedListener implements DialogInterface.OnClickListener {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      if (which == DialogInterface.BUTTON_POSITIVE) {
        result = OK;
      } else {
        result = CANCEL;
      }
      dialog.dismiss();
    }
  }
}

从MainActivity调用它:

if (MessageDialog.showConfirmDialog(this, "Do you want to delete?") == MessageDialog.OK) {
  // yes button was clicked
} else {
  // no button was clicked
}

但是点击哪个按钮并不重要,我总是得到点击是按钮的结果。

1 个答案:

答案 0 :(得分:-1)

这是因为show()方法异步显示警报,因此您的showConfirmDialog()方法始终返回OK值,然后您可以通过点击任何按钮来更改它。 为避免这种情况,您可以在onClick()方法

中处理不同的按钮行为

例如:

@Override
public void onClick(DialogInterface dialog, int which) {
  switch(which) {
    case DialogInterface.BUTTON_POSITIVE:
      // yes button behavior
      break;
    case DialogInterface.BUTTON_NEGATIVE:
      // no button behavior
      break;
  }

  dialog.dismiss();
}