Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom TextView in android with different color words

Is it possible to have a textview to have different color for every word? Or even every letter? I tried extending textview and creating it but however I thought of the problem is, how would I draw all the the text out at the same time with different colors?

like image 428
wtsang02 Avatar asked Jul 13 '12 23:07

wtsang02


People also ask

How do you change the color of your text on android?

Open your device's Settings app . Text and display. Select Color correction. Turn on Use color correction.

Which property is used to color text in TextView in android?

In XML, we can set a text color by the textColor attribute, like android:textColor="#FF0000" .


1 Answers

Use android.text.Spannable

final SpannableStringBuilder str = new SpannableStringBuilder(text);
str.setSpan(
    new ForegroundColorSpan(Color.BLUE), 
    wordStart, 
    wordEnd, 
    SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE
);
myTextView.setText(str);

EDIT: To make all "Java" green

final Pattern p = Pattern.compile("Java");
final Matcher matcher = p.matcher(text);

final SpannableStringBuilder spannable = new SpannableStringBuilder(text);
final ForegroundColorSpan span = new ForegroundColorSpan(Color.GREEN);
while (matcher.find()) {
    spannable.setSpan(
        span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    );
}
myTextView.setText(spannable);
like image 140
vasart Avatar answered Oct 14 '22 18:10

vasart