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

Ist*_*med 0 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();
Run Code Online (Sandbox Code Playgroud)

单击yes按钮显示在logcat中:yes id =:-1,no按钮同样显示:no id =:-2

因此,如何在参数值idonClick法确定的?

Par*_* P. 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;
Run Code Online (Sandbox Code Playgroud)

这就是为什么,它返回-1 !! 因为你点击了正面按钮和BUTTON_POSITIVE = -1