首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >android对话框按钮OnclickListener -如何确定id值

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

Stack Overflow用户
提问于 2017-03-21 20:16:41
回答 3查看 2.3K关注 0票数 0

MainActivity.java中创建警报对话框的简单代码:

代码语言:javascript
运行
复制
  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的值呢?

EN

回答 3

Stack Overflow用户

发布于 2017-03-21 20:20:57

粘贴DialogInterface类的代码-

代码语言:javascript
运行
复制
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

票数 5
EN

Stack Overflow用户

发布于 2017-03-21 20:33:21

对话框按钮常量如下所示

代码语言:javascript
运行
复制
int BUTTON_NEGATIVE = -2;
int BUTTON_NEUTRAL = -3;
int BUTTON_POSITIVE = -1;

因此,您可以将您的id与这些常量(访问常量如下)进行比较

代码语言:javascript
运行
复制
Dialog.BUTTON_NEGATIVE;
Dialog.BUTTON_POSITIVE;
Dialog.BUTTON_NEUTRAL;
票数 3
EN

Stack Overflow用户

发布于 2020-07-19 01:06:06

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42926918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档