我有以下TextView定义:

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="@string/txtCredits"
    android:autoLink="web" android:id="@+id/infoTxtCredits"
    android:layout_centerInParent="true"
    android:linksClickable="true"/>

其中@string/txtCredits是一个字符串资源,包含<a href="some site">链接文本</a>。

Android正在突出显示TextView中的链接,但它们不响应单击。我做错了什么?我必须在我的活动中为TextView设置一个onClickListener像这样简单吗?

它看起来和我定义字符串资源的方式有关。

这行不通:

<string name="txtCredits"><a href="http://www.google.com">Google</a></string>

但这确实是:

<string name="txtCredits">www.google.com</string>

这是一个遗憾,因为我宁愿显示一个文本链接,而不是显示完整的URL。


当前回答

这就是我如何解决TextView中可点击和可见的链接(通过代码)

private void setAsLink(TextView view, String url){
    Pattern pattern = Pattern.compile(url);
    Linkify.addLinks(view, pattern, "http://");
    view.setText(Html.fromHtml("<a href='http://" + url + "'>http://" + url + "</a>"));
}

其他回答

我希望这对你有帮助;

String value = "<html>Visit my blog <a href=\"http://www.maxartists.com\">mysite</a> View <a href=\"sherif-activity://myactivity?author=sherif&nick=king\">myactivity</a> callback</html>";
TextView text = (TextView) findViewById(R.id.text);

text.setText(Html.fromHtml(value));
text.setMovementMethod(LinkMovementMethod.getInstance());

我简单地用了这个:

Linkify.addLinks(TextView, Linkify.ALL);

它使链接可点击,这里给出。

我只使用android:autoLink=“web”,它工作得很好。单击该链接将打开浏览器并显示正确的页面。

我能猜到的一件事是,其他一些视图在链接的上方。透明的内容填充整个父元素,但不显示链接上方的任何内容。在这种情况下,点击指向这个视图而不是链接。

上面的解决方案对我没用,但是下面的解决方案对我有用(而且看起来更简洁)。 首先,在字符串资源中,使用HTML实体编码定义标签开头的v形符号,即:

&lt;a href="http://www.google.com">Google&lt;/a>

而不是:

<a href="http://www.google.com">Google</a>

一般来说,像这样编码字符串中的所有v形符号。顺便说一下,链接必须以http://开头

然后(正如这里所建议的)在你的TextView上设置这个选项:

 android:linksClickable="true"

最后,在代码中,执行以下操作:

((TextView) findViewById(R.id.your_text_view)).setMovementMethod(LinkMovementMethod.getInstance());
((TextView) findViewById(R.id.your_text_view)).setText(Html.fromHtml(getResources().getString(R.string.string_with_links)));

就是这样。不需要正则表达式或其他手工操作。

[预棒棒糖测试以及棒棒糖及以上测试]

您可以从后端或资源文件中获取HTML字符串。 如果你把文本作为资源字符串,请确保添加CDATA标签:

<string name="your_text">![CDATA[...<a href="your_link">Link Title</a>  ...]]</string>

然后在代码中,你需要获取字符串并将其赋值为HTML,并设置一个链接移动方法:

String yourText = getString(R.string.your_text);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
   textView.setText(Html.fromHtml(yourText, Html.FROM_HTML_MODE_COMPACT));
} else {
   textView.setText(Html.fromHtml(yourText));
}

try {
   subtext.setMovementMethod(LinkMovementMethod.getInstance());
} catch (Exception e) {
   //This code seems to crash in some Samsung devices.
   //You can handle this edge case base on your needs.
}