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.
Asked
Active
Viewed 2,471 times
1
-
Please post the code and layout screenshot to see how it looks. – blizzard May 31 '16 at 11:41
-
try `ReplacementSpan` instead – pskink May 31 '16 at 11:43
-
I do not believe that there is a built-in span that can handle your use case. You can try creating a custom span. Or, use multiple `TextViews`. Or, use a `WebView`. – CommonsWare May 31 '16 at 11:50
-
check this: http://stackoverflow.com/questions/19292838/android-spannablestring-set-background-behind-part-of-text – Mehta May 31 '16 at 11:54
2 Answers
2
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
-
1Thanks sir, but if i need add background is a image (not soild color), it is possible? – Truong Vu Jun 01 '16 at 02:36
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");

Armin Haghighi
- 66
- 1
- 6