单击EXIT按钮时不显示对话框

时间:2013-12-04 12:26:39

标签: android eclipse

我已经添加了一个对话框,只要我想要退出应用程序就会出现,当我按下退出按钮时出现。没有显示错误但退出按钮在我点击它时没有显示对话框。可以有人帮忙?

public void addListenerOnButton2()
{ 

    exit = (Button) findViewById(R.id.button2);
    exit.setOnClickListener(new OnClickListener() 
    {
        @Override
        public void onClick(View arg0) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
        MainActivity.this);
 alertDialogBuilder.setTitle("EXIT?");
 alertDialogBuilder
 .setMessage("Click yes to exit!")
 .setCancelable(false)
 .setPositiveButton("Yes",new DialogInterface.OnClickListener(){
     public void onClick(DialogInterface dialog,int id) {
         String exme = "Ok button Pressed";
 Toast t = Toast.makeText(MainActivity.this,exme, 
         Toast.LENGTH_SHORT); 
 t.show();
 MainActivity.this.finish();
     }
   })
   .setNegativeButton("No",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
            String exme1="Cancel button Pressed";
    Toast t1 = Toast.makeText(MainActivity.this,exme1, 
            Toast.LENGTH_SHORT); 
    t1.show();
    dialog.cancel();
        }
    });
 AlertDialog alertDialog = alertDialogBuilder.create();
 alertDialog.show();
        }
    });
}

1 个答案:

答案 0 :(得分:0)

Button exitButton = (Button) findViewById(R.id.button2);
exitButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view)
    {
        new AlertDialog.Builder(MainActivity.this)
        .setMessage("Click yes to exit!")
        .setCancelable(false)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(MainActivity.this, "Ok button Pressed", Toast.LENGTH_SHORT).show();
            }
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(MainActivity.this, "Cancel button Pressed", Toast.LENGTH_SHORT).show();
            }
        })
        .show();
    }
});