user3270441 user3270441 - 1 year ago 95
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 Source
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download