我在 TextView 中有一个字符串,我想链接该字符串的一个子字符串。例如:
点击这里了解更多。
我正在动态获取字符串。所以我必须搜索它是否有 click here 并将其转换为链接。我如何链接“click here”。
最佳答案
要在文本中查找模式并替换它,请使用:
Pattern p = Pattern.compile("click here");
Matcher m = p.matcher("for more info, click here");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
while(result) {
m.appendReplacement(sb, "<a href=\"www.mywebsite.com\">click here</a>");
result = m.find();
}
m.appendTail(sb);
String strWithLink = sb.toString();
yourTextView.setText(Html.fromHtml(strWithLink));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance())
此代码将在您的字符串中搜索并将所有“单击此处”替换为链接。
最后,不要将 android:autoLink="web"添加到您的 XML 资源(TextView 部分),否则 A 标签将无法正确呈现并且不再可点击。
关于android - linkyfy TextView 中的一些文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10883301/