17

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...

Lukap
  • 31,523
  • 64
  • 157
  • 244

3 Answers3

60

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

Kaj
  • 10,862
  • 2
  • 33
  • 27
  • 1
    Your answer should be marked as the correct one (not that the one marked correct is not, but I find this one the right approach). – Leeeeeeelo Jan 18 '13 at 08:46
  • I couldn't get this to work. The text comes out all black, even though one of the letters should be colored. What does the flag 0 even mean? It's not defined in the Spanned class. – FractalBob Mar 05 '22 at 21:02
2

Ah I found it use below code

myTextView.setText(Html.fromHtml(html text having 1 in red 2 in green and so on));

I dont know web so you better consult someone who can write html for you :P

ingsaurabh
  • 15,249
  • 7
  • 52
  • 81
1

You can prints lines with multiple colors without html like this:)

TextView TV = (TextView)findViewById(R.id.mytextview01);

  Spannable WordtoSpan = new SpannableString("Your message");        

WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 0, WordtoSpan .length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TV.setText(WordtoSpan);
Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92