在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();单击yes按钮显示logcat : yes id =:-1,单击no按钮类似地显示: no id =:-2
那么如何确定onClick方法中的参数id的值呢?
发布于 2017-03-21 20:20:57
粘贴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!!因为您正在单击positive按钮和 BUTTON_POSITIVE = -1
发布于 2017-03-21 20:33:21
对话框按钮常量如下所示
int BUTTON_NEGATIVE = -2;
int BUTTON_NEUTRAL = -3;
int BUTTON_POSITIVE = -1;因此,您可以将您的id与这些常量(访问常量如下)进行比较
Dialog.BUTTON_NEGATIVE;
Dialog.BUTTON_POSITIVE;
Dialog.BUTTON_NEUTRAL;发布于 2020-07-19 01:06:06
我相信上面的对话按钮常量现在都被弃用了。
https://stackoverflow.com/questions/42926918
复制相似问题