我有以下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。


当前回答

在正确格式化的HTML链接上使用setMovementMethod(LinkMovementMethod.getInstance())和HTML . fromhtml()时,请确保不要使用setAutoLinkMask(Linkify.ALL)(例如,<a href="http://www.google.com/">谷歌</a>)。

其他回答

如果使用基于xml的TextView,对于你的需求,你只需要做两件事:

识别字符串中的链接,例如“这是我的网页”。 您可以在XML内容或代码中添加它。 在有TextView的XML内容中,添加这些: android: linksClickable = " true " android: autoLink = "网络"

管理链接文本颜色也

tv_customer_care_no.setLinkTextColor(getResources().getColor(R.color.blue));
tv_customer_care_no.setText("For us to reach out to you, please fill the details below or contact our customer care at 18004190899 or visit our website http://www.dupont.co.in/corporate-links/contact-dupont.html");
Linkify.addLinks(tv_customer_care_no, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);
Linkify.addLinks(tv_customer_care_no, Linkify.ALL);

我希望这对你有帮助;

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());

对于那些从XML内容读取字符串和动态赋值有问题的人。

如果您正在使用来自strings.xml资源的文本,那么HTML标记似乎会被剥离。

所以你必须使用<![CDATA[**your string with click links**]]>在strings.xml文件中使用HTML . fromhtml (string)将其转换为HTML。

通过使用linkify:

Linkify获取一段文本和一个正则表达式,并将文本中的所有正则表达式匹配转换为可点击的链接:

TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("http://example.com");
Linkify.addLinks(textView, Linkify.WEB_URLS);

别忘了

import android.widget.TextView;