Android Webview 锚链接(跳转链接)不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3039555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:26:08  来源:igfitidea点击:

Android Webview Anchor Link (Jump link) not working

androidwebviewanchor

提问by Joel

I have a WebView in my Android App that is loading an HTML string using the loadDataWithBaseURL() method. The problem is that local anchor links (<a href="#link">...) are not working correctly. When the link is clicked, it becomes highlighted, but does not scroll to the corresponding anchor.

我的 Android 应用中有一个 WebView,它使用 loadDataWithBaseURL() 方法加载 HTML 字符串。问题是本地锚链接 ( <a href="#link">...) 无法正常工作。单击链接时,它会突出显示,但不会滚动到相应的锚点。

This also does not work if I use the WebView's loadUrl() method to load a page that contains anchor links. However, if I load the same URL in the browser, the anchor links do work.

如果我使用 WebView 的 loadUrl() 方法加载包含锚链接的页面,这也不起作用。但是,如果我在浏览器中加载相同的 URL,则锚链接确实有效。

Is there any special handling required to get these to work for a WebView?

是否需要任何特殊处理才能使它们适用于 WebView?

I am using API v4 (1.6).

我正在使用 API v4 (1.6)。

There isn't much to the code, here are the relevant parts of some test code I've been working with:

代码不多,以下是我一直在使用的一些测试代码的相关部分:

WebView detailBody = (WebView) findViewById(R.id.article_detail_body);
String s = "<a href=\"#link\">LINK!</a><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><a name=\"link\"></a>Testing!";
detailBody.loadDataWithBaseURL(API.HomeURL(this), s, "text/html", "utf-8", "");

采纳答案by Joel

It looks like the problem is that I had a WebView within a ScrollView. The WebView isn't able to scroll to an anchor link when configured like this. After refactoring my layout to eliminate the ScrollView, the anchor links work correctly.

看起来问题是我在 ScrollView 中有一个 WebView。像这样配置时,WebView 无法滚动到锚链接。重构我的布局以消除 ScrollView 后,锚链接正常工作。

回答by David Manpearl

Android Webview Anchor Link (Jump link) Not Working

Android Webview 锚链接(跳转链接)不起作用

True, WebView Anchor Links, or Jump Links initiated through the #LINK extension to the URL will not work when the WebView is inside of a ScrollView(*).

确实,当 WebView 位于 ScrollView(*) 内时,通过 URL 的 #LINK 扩展启动的 WebView 锚链接或跳转链接将不起作用。

Still, the problem for me and apparently others is that the #LINK does work when launched from a touch in an href, but is ignored when launched via the URL. Other symptoms include navigating to the link only on the first time in a session or navigating to the bottom of the html file.

尽管如此,对于我和其他人来说,问题在于 #LINK 在从 href 中的触摸启动时确实有效,但在通过 URL 启动时被忽略。其他症状包括仅在会话中第一次导航到链接或导航到 html 文件的底部。

The Solution is to load the url after a short delay.

解决方案是在短暂延迟后加载 url。

Here is an example:

下面是一个例子:

My html is saved in assets: res/assets/help.html

我的 html 保存在资产中: res/assets/help.html

With anchors like this:

使用这样的锚点:

<a name="helplinkcontacts"/>

And loaded like this:

并像这样加载:

final String baseUrl = "file:///android_asset/help.html#helplinkcontacts";
final WebView helpTextView = (WebView)findViewById(R.id.help_dialog_text);
helpTextView.loadUrl(baseUrl); // Ignores Anchor!!

I added the timer like this:

我添加了这样的计时器:

final String baseUrl = "file:///android_asset/help.html#helplinkcontacts";
final WebView helpTextView = (WebView)findViewById(R.id.help_dialog_text);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        helpTextView.loadUrl(baseUrl);
    }
}, 400);

Note: Shorter delays, such as 100ms failed to navigate to the link.

注意:较短的延迟,例如 100 毫秒无法导航到链接。

(*) It turns out that so many of us have our WebViews inside of ScrollViews because we started out with a TextView rendering Spannable text which both supports some HTML and requires a ScrollView. Anyways, remove the ScrollView as soon as you convert your TextView into a WebView.

(*) 事实证明,我们中的许多人在 ScrollView 中有我们的 WebView,因为我们从一个 TextView 开始呈现 Spannable 文本,它既支持一些 HTML,又需要一个 ScrollView。无论如何,一旦将 TextView 转换为 WebView,请立即删除 ScrollView。

回答by MKJParekh

My Solution is , Check this Answer

我的解决方案是,检查这个答案

public class MainActivity extends Activity { 
    WebView myWebView; 
    public static boolean flag = false; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        myWebView = new WebView(this); 
        myWebView.getSettings().setJavaScriptEnabled(true); 
        myWebView.loadUrl("file:///android_asset/chapters.html"); 
        setContentView(myWebView); 
        myWebView.setWebViewClient(new WebViewClient() { 
            public void onPageFinished(WebView view, String url) { 
                if (url.contains("#") && flag == false) { 
                    myWebView.loadUrl(url); 
                    flag = true; 
                } else { 
                    flag = false; 
                } 
            } 

        }); 
    } 
} 

回答by Ujjwal Goyal

I was also facing the same issue. Anchor link was jumping to arbitrary position. Make sure not to hide webviewwhen loading.

我也面临同样的问题。锚链接跳到任意位置。确保webview在加载时不要隐藏。

Use Invisibleinstead of gone.

使用Invisible代替gone

This change fixed my issue.

此更改解决了我的问题。

回答by Peter McKeown

WebView in Android 4.0 fails to open URLs with links in them. e.g. "file:///android_asset/help.html#helplinkcontacts"

Android 4.0 中的 WebView 无法打开包含链接的 URL。例如“file:///android_asset/help.html#helplinkcontacts”

Here is how I got around it

这是我绕过它的方法

WebView wv = (WebView) nagDialog.findViewById(R.id.wv);
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebViewClient(new MyWebViewClient(link));
wv.loadUrl("file:///android_asset/help.html");

And define the custom WebViewClient class

并定义自定义的 WebViewClient 类

class MyWebViewClient extends WebViewClient {
    private String link;

    public MyWebViewClient(String link) {
        this.link = link;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (!"".equals(link) && link != null)
            view.loadUrl("javascript:location.hash = '#" + link + "';");
    }
}

回答by ubzack

I had a similar problem. Nothing would jump to anchor tags in the html. I didn't have my WebView within a ScrollView. Instead the problem was the base url I passed into loadDataWithBaseURL did not have a colon (':') in it. I believe the baseUrl needs to have some text, then a colon, then some more text, for example "app:htmlPage24".

我有一个类似的问题。没有什么会跳转到 html 中的锚标记。我在 ScrollView 中没有我的 WebView。相反,问题是我传递给 loadDataWithBaseURL 的基本 url 中没有冒号 (':')。我相信 baseUrl 需要有一些文本,然后是一个冒号,然后是更多的文本,例如“app:htmlPage24”。

So here's the initial call to my WebView, just to load the data in the string HTML_24:

所以这是对我的 WebView 的初始调用,只是为了加载字符串 HTML_24 中的数据:

wv.loadDataWithBaseURL("app:htmlPage24", HTML_24, "text/html", "utf-8", null);

Then I have a list that jumps to sections on the screen, depending on the list item you tap:

然后我有一个列表,它跳转到屏幕上的部分,具体取决于您点击的列表项:

sectionsLV.setOnItemClickListener(new OnItemClickListener()
{
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
    {
        wv.loadUrl("app:htmlPage24#section" + arg2);
    }
});

HTML_24 is something like:

HTML_24 类似于:

<html>
...
<a name="section1"/>

...
<a name="section2"/>

...
<a name="section3"/>

...
</html>

回答by Jorgesys

try this

String myTemplate = "<a href=\"#link\">LINK!</a><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><a name=\"link\"></a>Testing!";

myWebView.loadDataWithBaseURL(null, myTemplate, "text/html", "utf-8", null);

the word "Testing!" must be outside of the screen to see it works.

“测试!”这个词 必须在屏幕之外才能看到它的工作原理。