MainActivity.java
中的简单代码来创建警报对话框:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Your Title")
.setMessage("Click yes or exit")
.setCancelable(false)
.setIcon(R.drawable.icon)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id ){
Log.v(" yes id = ",id+"");
MainActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Log.v(" no id = ",id+"");
dialog.cancel();
}
});
AlertDialog alertDialog= alertDialogBuilder.create();
alertDialog.show();
单击"是"按钮显示在logcat中:是ID =:-1"否"按钮同样显示:无 id =: -2
那么onClick
方法内部的参数id
的值是如何确定的呢?
粘贴DialogInterface
类的代码 -
interface OnClickListener {
/**
* This method will be invoked when a button in the dialog is clicked.
*
* @param dialog The dialog that received the click.
* @param which The button that was clicked (e.g.
* {@link DialogInterface#BUTTON1}) or the position
* of the item clicked.
*/
/* TODO: Change to use BUTTON_POSITIVE after API council */
public void onClick(DialogInterface dialog, int which);
}
public static final int BUTTON1 = BUTTON_POSITIVE;
public static final int BUTTON_POSITIVE = -1;
这就是为什么,它返回 -1!! 因为您正在单击正面按钮并BUTTON_POSITIVE = -1
对话框按钮常量如下
int BUTTON_NEGATIVE = -2;
int BUTTON_NEUTRAL = -3;
int BUTTON_POSITIVE = -1;
因此,您可以将您的 id 与这些常量进行比较(访问常量如下所示(
Dialog.BUTTON_NEGATIVE;
Dialog.BUTTON_POSITIVE;
Dialog.BUTTON_NEUTRAL;
我相信上面的对话框按钮常量现在都已弃用。