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


当前回答

管理链接文本颜色也

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

其他回答

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

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

上面的解决方案对我没用,但是下面的解决方案对我有用(而且看起来更简洁)。 首先,在字符串资源中,使用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)));

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

对我来说,最简单的方法就是使用Linkify

TextView txt_Message = (TextView) view.findViewById(R.id.txt_message);
txt_Message.setText("This is link https://www.google.co.in/");
Linkify.addLinks(txt_Message, Linkify.WEB_URLS);

它将自动检测web url从文本在textview。

将此添加到您的EditText:

android:autoLink="web"
android:linksClickable="true"

我只是浪费了很多时间来弄清楚你必须使用getText(R.string.whatever)而不是getString(R.string.whatever)…

总之,我是这么做的。在同一个文本视图中也有多个超链接。

TextView termsTextView = (TextView) getActivity().findViewById(R.id.termsTextView);
termsTextView.append("By registering your account, you agree to our ");
termsTextView.append(getText(R.string.terms_of_service));
termsTextView.append(", ");
termsTextView.append(getText(R.string.fees));
termsTextView.append(", and the ");
termsTextView.append(getText(R.string.stripe_connected_account_agreement));

termsTextView.setMovementMethod(LinkMovementMethod.getInstance());

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/termsTextView"/>

字符串的例子:

    <string name="stripe_connected_account_agreement"><a href="https://stripe.com/connect/account-terms">Stripe Connected Account Agreement</a></string>