user3270441 user3270441 - 2 months ago 8
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

Answer
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()) {
    spannableBuilder.setSpan(
        span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
yourTextView.setText(spannableBuilder);

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

See More About Pattern Here

Comments