且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按下返回按钮可退出应用程序,而不是在WebView中向后导航

更新时间:2023-01-10 11:18:19

将此添加到您的 Activity 代码中(不在 onCreate()中或嵌套在其他任何地方)>

Add this in your Activity code (not in onCreate() or nested anywhere else)

@Override
public void onBackPressed() {
    if (web.copyBackForwardList().getCurrentIndex() > 0) {
        web.goBack();
    }
    else {
        // Your exit alert code, or alternatively line below to finish
        super.onBackPressed(); // finishes activity
    }
}

这将在 WebView 历史记录堆栈中导航,直到其为空,然后执行默认操作(在这种情况下,它完成了活动).

This will navigate back through the WebView history stack until it is empty and then perform the default action (in this case it finishes the activity).

您可能还应该将WebViewClient设置为使 shouldOverrideUrlLoading 返回 true ,否则您将不会加载任何链接.

You should probably also set your WebViewClient to have shouldOverrideUrlLoading return true or you won't load any links.