首页 > 解决方案 > 如何从全文中查找特定单词并使其超链接可使用 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());

标签: androidhyperlinktextviewspannablestring

解决方案


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


推荐阅读