Add your own BackgroundColorSpan
as you see fit.
Here is some code that sets such a span on all occurrences of a search term within a TextView
:
private void searchFor(String text) {
TextView prose=(TextView)findViewById(R.id.prose);
Spannable raw=new SpannableString(prose.getText());
BackgroundColorSpan[] spans=raw.getSpans(0,
raw.length(),
BackgroundColorSpan.class);
for (BackgroundColorSpan span : spans) {
raw.removeSpan(span);
}
int index=TextUtils.indexOf(raw, text);
while (index >= 0) {
raw.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
+ text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
index=TextUtils.indexOf(raw, text, index + text.length());
}
prose.setText(raw);
}
So, find your beginning and ending points, create a BackgroundSpan
with your desired color, and use setSpan()
to apply it.
Note that this assumes that only part of your text needs the background color. If the entire TextView
needs the color, go with njzk2's suggestion, and just apply the color to the whole TextView
.