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



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;

我相信上面的对话框按钮常量现在都已弃用。

相关内容

  • 没有找到相关文章

最新更新