首页 > 解决方案 > 如何防止后退按钮,直到确认消息?

问题描述

在 Android Studio 中,我使用了 WebView。因此,如果用户单击后退按钮,我想在应用关闭之前显示一条确认消息。

这是我当前使用的代码,但并非每次都有效

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();
}

标签: javaandroidwebview

解决方案


上面的代码工作正常。如果您想将 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();
  }
}

推荐阅读