user3270441 user3270441 - 9 months ago 57
Java Question

Setting Different Color For Text Inside A TextView Android

I have put in my app one textview inside a fragment. Each page has a different text. I want every time you find for example the word "tree", this word is painted color red and the rest words white. How could I do it? thanks

Pattern pattern = Pattern.compile("tree");
Matcher matcher = pattern.matcher(yourTextViewText);

final SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(yourTextViewText);
final ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
while (matcher.find()) {
        span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

This will replace all the word "tree" with RED Color.

See More About Pattern Here