android对话框按钮OnclickListener - 如何确定id值

时间:2017-03-21 12:16:41

标签: android dialog android-dialog

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

那么id方法中的参数onClick的值是如何确定的?

3 个答案:

答案 0 :(得分:5)

粘贴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

答案 1 :(得分:1)

对话框按钮常量如下

int BUTTON_NEGATIVE = -2;
int BUTTON_NEUTRAL = -3;
int BUTTON_POSITIVE = -1;

所以你可以将你的id与这些常量进行比较(访问常量如下)

Dialog.BUTTON_NEGATIVE;
Dialog.BUTTON_POSITIVE;
Dialog.BUTTON_NEUTRAL;

答案 2 :(得分:0)

我相信上述Dialog Button常量现在都已弃用。