[英]How to prevent back button until confirmation message?
In Android Studio, I've used a WebView. 在Android Studio中,我使用了WebView。 So if a user clicks the back button, I want to show a confirmation message before app close.
因此,如果用户单击“后退”按钮,我想在应用关闭之前显示一条确认消息。
This is my current code which I used, but it is not working every time 这是我当前使用的代码,但并非每次都有效
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
The above code is working fine. 上面的代码工作正常。 If you want to navigate the WebView back to the previous page use below one.
如果要将WebView导航回到上一页,请使用下面的页面。
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
}else{
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
super.onBackPressed();
}
})
.setNegativeButton("No", null)
.show();
}
}
You have to call your confirmation message method inside your Activities onBackPressed
Method 您必须在Activity
onBackPressed
方法内调用确认消息方法
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
onBackPressed() // This is Your Confirmation Dialog method
}
}
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
// If web view have back history, then go to the web view back history
webView.goBack();
} else {
// Ask the user to exit the app or stay in here
exitApp();
}
}
public void exitApp() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Please confirm");
builder.setMessage("Do you want to exit the app?");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
// Create the alert dialog using alert dialog builder
AlertDialog dialog = builder.create();
// Finally, display the dialog when user press back button
dialog.show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.