Basic internal links don't work in honeycomb app?

空扰寡人 提交于 2019-12-01 03:27:25

Here is the solution I use. Works the same on all Android platform (tested on all 1.6 to 4.0.1)

Load the file as you would normally, without the anchor point. E.g.:

webview.loadUrl("file:///android_asset/file.html");

Load the URL without the anchor point (e.g. file:///android_asset/file.html), and add:

webview.setWebViewClient(new WebViewClient()
{
    public void onPageFinished(WebView view, String url)
    {
        if (this.anchor != null)
        {
            view.loadUrl("javascript:window.location.hash='" + this.anchor + "'");
            this.anchor = null;
        }
    }
});

where anchor is the anchor point you want to jump to.

you have to make sure javascript is enabled:

WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);

This is for loading the file into the webview. Now if you want to catch internal links that are now broken, as suggested in the other answer, override the onReceivedError method and insert do something like:

    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
    {
        int found = failingUrl.indexOf('#');

        if (found > 0)
        {
            anchor = failingUrl.substring(found + 1, failingUrl.length());
            view.loadUrl(failingUrl.substring(0, found));
        }
    }

Here is my workaround code so the bug is transparent to the user.
Define the WebViewClient for the browser, and include something like the following for onReceivedError:

        @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
    {
        if (failingUrl.contains("#")) {
            Log.v("LOG", "failing url:"+ failingUrl);
            final int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
            if (sdkVersion > Build.VERSION_CODES.GINGERBREAD) {
                String[] temp;
                temp = failingUrl.split("#");
                view.loadUrl(temp[0]); // load page without internal link

                try {
                    Thread.sleep(400);
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
            }

            view.loadUrl(failingUrl);  // try again
        } else {
             view.loadUrl("file:///android_asset/tableofcontents.html");
        }
    }
    });

This tricks the webview to first load the page without the #link, then sleep for .4 of a second, and then load the full URL again. I have chosen to do this trick for tablets only by sdkVersion. If there is any other error I load another page, the tableofcontents.html. This works to fix the problem on my Galaxy Tab.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!