简体   繁体   English

如何设置警报对话框以正确显示?

[英]how to set an alert dialog to be shown correctly?

I have a button in my app and I want to show a Alert Dialog when I press that button. 我的应用程序中有一个按钮,当我按下该按钮时,我想显示一个警报对话框。 I tried to do it but didn't work.I'll be tankful if anyone can help me. 我试着做但是没用。如果有人可以帮助我,我会很坦率的。 here's my code 这是我的代码

   cancelBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            AlertDialog.Builder builder=new AlertDialog.Builder(getApplicationContext());

            builder.setMessage("unsaved content.are you sure you want to abort operation ?");

            builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    clearAll();

                }


            });


            builder.setNegativeButton("no",new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                     dialog.cancel();

                }
            } );


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


        }
    });

I think it needs to be 我认为这应该是

AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);

instead of 代替

AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

where MyActivity is the Activity where you have written this code. 其中MyActivity是您编写此代码的Activity

Also, you forgot to add 另外,您忘记添加

builder.setTitle("Title");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM