android - 如何从全文中查找特定单词并使其超链接可使用 textview 单击?
问题描述
我正在使用 textview 并设置从 json 获得的文本,
“这是我们的联系我们页面,请致电我们”
我从服务器获取的上述文本并显示在第三个 recyclerview 项目上,现在我正在尝试在任何列表项中,如果有“联系人”字样,我正在尝试将其设置为超链接并希望使其可点击。但它不工作。
String fulltext=brandList.get(position).getFAQAnswerText();
String match="contact";
if (fulltext.contains(match)) {
System.out.println("Keyword matched the string" );
ss = new SpannableString(fulltext);
ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 6,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new URLSpan("tel:4155551212"), 13, 17,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
holder.tvans.setText(ss);
holder.tvans.setMovementMethod(LinkMovementMethod.getInstance());
解决方案
textView.setText("this is clickable text");
if (fulltext.contains("clickable")) {
setClickableHighLightedText(textView, "clickable", new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO: do your stuff here
}
});
}
将此方法放在您的 Util 类中。
/**
* use this method to set clickable highlighted a text in TextView
*
* @param tv TextView or Edittext or Button or child of TextView class
* @param textToHighlight Text to highlight
*/
public void setClickableHighLightedText(TextView tv, String textToHighlight, View.OnClickListener onClickListener) {
String tvt = tv.getText().toString();
int ofe = tvt.indexOf(textToHighlight, 0);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
if (onClickListener != null) onClickListener.onClick(textView);
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(tv.getContext().getResources().getColor(R.color.colorPrimary));
ds.setUnderlineText(true);
}
};
SpannableString wordToSpan = new SpannableString(tv.getText());
for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
ofe = tvt.indexOf(textToHighlight, ofs);
if (ofe == -1)
break;
else {
wordToSpan.setSpan(clickableSpan, ofe, ofe + textToHighlight.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
输出
更新
更改跨度颜色
@Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setColor(tv.getContext().getResources().getColor(R.color.spanColor)); }
更改高亮/onTouch 颜色
textView.setHighlightColor(getResources().getColor(R.color.onTouchColor));
推荐阅读
- typescript - Typescript 和 @octokit/webhooks.js:基于 `EmitterWebhookEventName` 约束事件类型
- vb.net - 不允许创建新行,但文本框仍然是带有 wordwarp 的多行
- java - 圆形水平回收器视图适配器
- zsh - 从 zsh CLI 将数组作为输入变量传递到 Ruby 文件中
- android - 动态数据添加到数据集时折线图图形闪烁
- tensorflow - 二进制分类未正确训练
- bash - Makefile 变量没有扩展到正确的值
- parallel-processing - 在矩阵向量乘法中使用 OpenMP“for simd”?
- python - 即使使用 QueueHandler QueueListener,Python 日志记录也会减慢代码速度
- python - 防止python在用户输入后显示用户输入的输入行(他应该能够看到他在输入什么)