Can textview have letters in different colors?

Lukap picture Lukap · Jun 8, 2011 · Viewed 14.6k times · Source

I want to display '123' but 1 in red color 2 in green and 3 in black ... Is that possible, or is there any other recommended way of displaying different text color in the same textview...

Answer

Kaj picture Kaj · Jun 8, 2011

Yes, you can have different colors in different places of the text if you are using SpannableString. Example:

SpannableString text = new SpannableString("Lorem ipsum dolor sit amet");  
// make "Lorem" (characters 0 to 5) red  
text.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);  
textView.setText(text, BufferType.SPANNABLE);

There's a more complete example here.

Javadoc for SpannableString