我正在尝试完成应用程序中的主菜单。我认为在OnBackPressed方法中添加一个AlertDialog会是个简单又好看的点缀。然而,出于某种原因,我遇到了各种错误。
我在OnBackPressed方法中创建了AlertDialog并显示它,但当我按下返回按钮时,应用程序会直接关闭,并显示窗口泄漏的错误信息。
有什么办法可以解决这个问题吗?我已经搜索了大约30分钟,但找不到其他人遇到类似问题的情况。
我正在尝试完成应用程序中的主菜单。我认为在OnBackPressed方法中添加一个AlertDialog会是个简单又好看的点缀。然而,出于某种原因,我遇到了各种错误。
我在OnBackPressed方法中创建了AlertDialog并显示它,但当我按下返回按钮时,应用程序会直接关闭,并显示窗口泄漏的错误信息。
有什么办法可以解决这个问题吗?我已经搜索了大约30分钟,但找不到其他人遇到类似问题的情况。
尽量不要调用 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中添加了一个名为onSuperBackPressed
的新公共方法,并使用super
方法。
感谢K_Anas提供了这个绝妙的想法。
在你的对话框中调用 yourActivity.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()
的代码...虽然我不确定你想做什么是个好主意。 - Squonk