1

For example, I have a textview (multi line): aaaaaaaaabbbbaaa. I want to set background for only 'bbb' characters. I try to use Spannable but it doesn't work with my background is a image from drawable. Many thanks.

Truong Vu
  • 204
  • 4
  • 14

2 Answers2

2

enter image description here

using BackgroundColorSpan you can do that ,but Chinese doesn`t work in right way .

 private void replaceText(TextView text, String str, int color) {
    Spannable raw = new SpannableString(text.getText());
    BackgroundColorSpan[] spans = raw.getSpans(0,raw.length(),BackgroundColorSpan.class);

    for (BackgroundColorSpan span : spans) {
        raw.removeSpan(span);
    }
    int index = TextUtils.indexOf(raw, str);
    while (index >= 0) {
        raw.setSpan(new BackgroundColorSpan(color), index, index + str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        index = TextUtils.indexOf(raw, str, index + str.length());
    }
    text.setText(raw);
}
moonChen
  • 107
  • 2
0
private fun highlightTextPart(
    textView: TextView,
    mainString: String,
    subString: String
) {


    if (mainString.contains(subString)) {
        val startIndex = mainString.indexOf(subString)
        val endIndex = startIndex + subString.length
        val spannableString = SpannableString(mainString)
        spannableString.setSpan(
            BackgroundColorSpan(Color.parseColor("#ff00ff")),
            startIndex,
            endIndex,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        textView.text = spannableString
    }
}

using

    highlightTextPart("text text sell text", textView, "sell");