我有以下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。
我使用自动链接来“自动下划线”文本,但我只是做了一个“onClick”来管理它(我自己遇到了这个问题)。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:textSize="18dp"
android:autoLink="all"
android:text="@string/twitter"
android:onClick="twitter"/>
public void twitter (View view)
{
try
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://twitter.com/onaclovtech"));
startActivity(browserIntent);
}
finally
{
}
}
它不需要任何权限,因为你将意图传递给管理这些资源的应用程序(即浏览器)。
这对我来说很管用。
你可以简单地添加链接到你的TextView与Android的Linkify库。
添加到你的strings.xml
<string name="text_legal_notice">By continuing, you confirm that you have read, understood and agreed to our %1$s and %2$s.</string>
<string name="text_terms_conditions">Terms & Conditions</string>
<string name="text_privacy_policy">Privacy Policy</string>
加入到你的活动中
final String termsConditionsText = getString(R.string.text_terms_conditions);
final String privacyPolicyText = getString(R.string.text_privacy_policy);
final String legalText = getString(
R.string.text_legal_notice,
termsConditionsText,
privacyPolicyText
);
viewBinding.textViewLegalNotice.setText(legalText);
Linkify.addLinks(
viewBinding.textViewLegalNotice,
Pattern.compile(termsConditionsText),
null,
null,
(match, url) -> "https://policies.google.com/terms"
);
Linkify.addLinks(
viewBinding.textViewLegalNotice,
Pattern.compile(privacyPolicyText),
null,
null,
(match, url) -> "https://policies.google.com/privacy"
);
[预棒棒糖测试以及棒棒糖及以上测试]
您可以从后端或资源文件中获取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.
}