简体   繁体   English

如何在HTML中点击链接? (机器人)

[英]How can I make links in fromHTML clickable? (Android)

This seems like a trivial problem, but is has me kind of stumped. 这似乎是一个微不足道的问题,但是让我有些难过。 I want to load an HTML string using Html.fromHtml(), and have any links in the string to be clickable and open in the browser. 我想使用Html.fromHtml()加载HTML字符串,并且字符串中的任何链接都可以在浏览器中单击并打开。

Basic example: 基本示例:

textView.setText(Html.fromHtml("<a href=\"http://www.google.com\">This is a link</a>"));

With this snippet, the text is formatted as if it were a link (blue, underlined), but it's not clickable. 使用此代码段,文本的格式就像是一个链接(蓝色,带下划线),但它不可点击。 I tried Linkify, but it only seems to work with links that are not HTML-based. 我尝试过Linkify,但它似乎只适用于非基于HTML的链接。

Any suggestions? 有什么建议?

As I assumed, the solution was trivial: 正如我所假设的那样,解决方案很简单:

textView.setText(Html.fromHtml("<a href=\"http://www.google.com\">This is a link</a>"));
textView.setMovementMethod(LinkMovementMethod.getInstance());

The second line somehow activates the link behavior, although I'm not quite sure how. 第二行以某种方式激活链接行为,虽然我不太确定如何。 The same question is addressed over at Google Code . Google Code上也解决了同样的问题。

As mentioned in other answers, a way forward is to use: 正如其他答案中所提到的,前进的方法是使用:

xtView.setText(Html.fromHtml("<a href=\"http://www.google.com\">This is a link</a>"));
textView.setMovementMethod(LinkMovementMethod.getInstance());

However, this won't work if you have ANY android:autoLink value set, not just 'web' as other comments seem to suggest. 但是,如果你有任何android:autoLink值设置,这不会起作用,而不仅仅是'web',正如其他评论似乎暗示的那样。 So that means you can use this solution to linkify URLs at the expense of having phone, email and maps being disabled/unlinked. 这意味着您可以使用此解决方案来链接URL,但代价是禁用/取消链接电话,电子邮件和地图。

The javadoc of the LinkMovementMethod says that it LinkMovementMethod的javadoc说它

Supports clicking on links with DPad Center or Enter. 支持单击DPad Center或Enter的链接。

So it makes sense that works that way. 因此,以这种方式工作是有意义的。

And confirmed, with 4.2.2 works like charm with just the 并且确认,4.2.2的作品就像魅力一样

textView.setMovementMethod(LinkMovementMethod.getInstance());

It should be this way: 它应该是这样的:

textView.setText(Html.fromHtml("<a href=\"http://www.google.com\">This is a link</a>"));
textView.setAutoLinkMask(Linkify.WEB_URLS);
textView.setLinksClickable(true);

in XML should be 在XML中应该是

<TextView
    android:id="@+id/txtview"
    android:autoLink="web"
    android:linksClickable="true"
    />
String data="MyTest";

textView.setText(data);
textView.setText(Html.fromHtml(data));
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setLinksClickable(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM