带有警告对话框的 Android 退出按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24504103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:18:23 来源:igfitidea点击:
Android Exit button with alert dialog
提问by jana
I am using the following code to exit my application.
我正在使用以下代码退出我的应用程序。
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
now when i press the exit, it should show the alert dialog. if i pressed ok, close the application otherwise no.
现在当我按下退出时,它应该显示警报对话框。如果我按确定,关闭应用程序,否则没有。
回答by Jawad Zeb
remove super.OnBackPressed()
删除 super.OnBackPressed()
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
回答by Ranjit
Check the total alertdialog code from this link..and in the positive button write like:
.setPositiveButton("Logout",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//your_activity.finish();......(1)
//otherwise use your code..
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});