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

时间:2015-02-21 18:47:49

标签: android android-activity

我的应用程序中有一个按钮,当我按下该按钮时,我想显示一个警告对话框。我试着这样做,但没有工作。如果有人能帮助我,我会很坦然。 这是我的代码

   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();


        }
    });

1 个答案:

答案 0 :(得分:0)

我认为需要

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

而不是

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

其中MyActivity是您编写此代码的Activity

另外,您忘了添加

builder.setTitle("Title");