如何显示警报按钮?

时间:2020-09-24 02:20:23

标签: android

我看不到我的按钮...。它只是显示一条消息....请帮助我....

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("delete?");
        builder.create().show();
        builder.setPositiveButton("yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        builder.setNegativeButton("no",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

3 个答案:

答案 0 :(得分:0)

这是因为您要先创建AlertDialog,然后将按钮设置为AlertDialog。尝试下面的代码

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("delete?");       
builder.setPositiveButton("yes",
    new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
     });
     builder.setNegativeButton("no",
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
     });
builder.create().show();

答案 1 :(得分:0)

您正在尝试在设置之前创建对话框。

将以下代码移到现有代码的末尾

builder.create().show();

最终代码如下:


AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("delete?");       
    builder.setPositiveButton("yes",
    new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            
        }
        
    });
    builder.setNegativeButton("no",
    new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            
        }
        
    });
    
    builder.create().show();    //this is the line that has been moved

答案 2 :(得分:0)

创建builder.setPositiveButton之前,必须先致电AlertDialogBuilder

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("delete?");
        builder.setPositiveButton("yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        builder.setNegativeButton("no",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

       builder.create().show();