You can easily do this by using SpannableString
. Let's say that you want to colour abc
in the string fooabcbar
green:
String s = "fooabcfoo";
SpannableString spannable = new SpannableString(s);
spannable.setSpan(new ForegroundColorSpan(Color.GREEN), 3, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE));
view.setText(spannable)
This is essentially what Html.fromHtml()
suggested by jackson95 does behind the scenes.
The last parameter to .setSpan()
controls how the span changes when characters are inserted at the edge of the span. "exclusive" means that the span will not extend to cover a new character. If the TextView
is not editable, then it doesn't actually matter what you put there.
You can add any number of spans to a string, so you can easily loop through the string, looking for words to highlight and simply add spans for each one.
There are plenty of other spans one can add, that controls things such as fonts and other types of decoration. You can even create your own spans that call arbitrary drawing commands, This is done by implementing the .draw()
method in ReplacementSpan
.