Android在按下时提示AlertDialog
我正试图在我的应用程序中完成我的主菜单。我认为在OnBackPressed方法中添加AlertDialog是一个简单的好方法。然而由于某种原因,我得到了各种各样的错误 我在OnBackPressed中创建了AlertDialog并显示它,但当我按下back按钮时,应用程序刚好关闭,我收到错误消息,说窗口正在泄漏 你知道怎么解决这个问题吗?我搜索了大约30分钟,没有找到其他有这个问题的人 我在OnBackPressed中创建了AlertDialog并显示它,但当我按下back按钮时,应用程序刚好关闭,我收到错误消息,说窗口正在泄漏Android在按下时提示AlertDialog,android,android-alertdialog,Android,Android Alertdialog,我正试图在我的应用程序中完成我的主菜单。我认为在OnBackPressed方法中添加AlertDialog是一个简单的好方法。然而由于某种原因,我得到了各种各样的错误 我在OnBackPressed中创建了AlertDialog并显示它,但当我按下back按钮时,应用程序刚好关闭,我收到错误消息,说窗口正在泄漏 你知道怎么解决这个问题吗?我搜索了大约30分钟,没有找到其他有这个问题的人 我在OnBackPressed中创建了AlertDialog并显示它,但当我按下back按钮时,应用程序刚好关
如果在
OnBackPressed
中调用了super.OnBackPressed()
,则应用程序将完成,因为OnBackPressed
的基本实现就是这样做的。不要调用super
方法,应用程序将不会关闭。尝试不要调用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();
}
如果要调用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) {
//finish();
MyActivity.this.onSuperBackPressed();
//super.onBackPressed();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
/*
if (handleCancel()){
super.onBackPressed();
}
*/
}
public void onSuperBackPressed(){
super.onBackPressed();
}
我刚刚在MyActivity中添加了一个新的public方法onSuperBackPressed
,使用super
-方法
感谢您提供了极好的想法。在对话框中调用您的Activity.this.onBackPressed()
utility.makeAlertDialog("Cancel Verification","Do you want to cancel the verification process","Cancel Verification",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
utility.failureToast("OTP verification");
Intent intent = new Intent(MobileOTPActivity.this,MobileNumberLoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
MobileOTPActivity.this.onBackPressed();
}
},"Close");
显示
onBackPressed()
…的代码,尽管我不确定您试图做的是一个好主意。按下后退按钮时显示的AlertDialogs(即“确认退出”对话框)严重降低了用户体验。我以前也这么做过,当我在后续版本中删除它们时,我的应用程序看起来快了很多,这让我非常惊讶。除非你真的,真的,真的需要,否则不要使用它们:)@AlexLockwood你会说,如果用户所做的更改因为简单的返回而丢失,我真的,真的,真的需要显示一个警报对话框吗?