Can textview have letters in different colors? [duplicate]
Asked Answered
D

3

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

Danieldaniela answered 8/6, 2011 at 13:26 Comment(2)
I dont have the code but it can be done using html textHarass
why that ?? you make a linearlayout and inflate texteview insade has many as you want :DCalyces
H
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

Harass answered 8/6, 2011 at 13:32 Comment(3)
tnx , here is something more coplete String styledText ="<font color='red'>asd</font>"; cache.timeView.setText(Html.fromHtml(styledText) );Danieldaniela
I don't think that using html is the right way to go.Uncrowned
Why does the html is not the right way @Kaj?Caraviello
U
58

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

Uncrowned answered 8/6, 2011 at 13:32 Comment(2)
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).Sportsmanship
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.Poachy
H
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

Harass answered 8/6, 2011 at 13:32 Comment(3)
tnx , here is something more coplete String styledText ="<font color='red'>asd</font>"; cache.timeView.setText(Html.fromHtml(styledText) );Danieldaniela
I don't think that using html is the right way to go.Uncrowned
Why does the html is not the right way @Kaj?Caraviello
M
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);
Maury answered 8/6, 2011 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.