按下返回按钮可退出应用程序,而不是在WebView中向后导航 [英] Pressing back button exits the app instead of navigating backwards in the WebView

查看:71
本文介绍了按下返回按钮可退出应用程序,而不是在WebView中向后导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WebView android应用程序.我无法解决我的应用中的问题以向后导航.我正在使用此代码,并尝试过对此进行所有修改.

I am working on a WebView android app. I am unable to fix an issue in my app to back navigate. I am using this code and tried all modifications can be made to this.

public class DeviceActivity extends Activity {
    private WebView web;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        web = (WebView) findViewById(R.id.webView);
        web.getSettings().setJavaScriptEnabled(true);
        web.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
        web.getSettings().setPluginsEnabled(false);
        web.getSettings().setSupportMultipleWindows(false);
        web.getSettings().setSupportZoom(false);
        web.setVerticalScrollBarEnabled(false);
        web.setHorizontalScrollBarEnabled(false);

        // Our application's main page will be loaded
        web.loadUrl("file:///android_asset/fbp/index.html");

        web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            public void onBackPressed() {
                if (web.canGoBack()) {
                    web.goBack();
                } else {
                    // My exit alert code goes here.
                }
            }
        });
    }
}

这不会向后导航,而是退出应用程序.任何帮助将不胜感激.

This doesn't navigate back but instead, it exits the app. Any help would be appreciated.

推荐答案

将此添加到您的 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.

这篇关于按下返回按钮可退出应用程序,而不是在WebView中向后导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆