将退出对话框实现到android活动中

时间:2013-02-26 19:15:13

标签: android

我正在尝试在按下后退按钮时向用户实现退出对话框,但是当他按下它时,它会将他发送到先前的活动而不显示对话框。

以下是onBackPressed():

        @Override
        public void onBackPressed() {
        new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Closing Activity")
            .setMessage("Are you sure you want to close this activity?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();    
            }

        })
        .setNegativeButton("No", null)
        .show();
    }

1 个答案:

答案 0 :(得分:0)

只需添加.Create(),只需添加super.finish()即可退出父活动。

public void onBackPressed() {
 new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Closing Activity")
        .setMessage("Are you sure you want to close this activity?")
        .setPositiveButton("Yes", new DialogInterface.OnClickListener()
       {
        @Override
        public void onClick(DialogInterface dialog, int which) {
           super.finish();    
        }

        })
      .setNegativeButton("No", null)
      .create().show();
}