Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can textview have letters in different colors? [duplicate]

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

like image 302
Lukap Avatar asked Jun 08 '11 13:06

Lukap


People also ask

How can I change the color of part of a string in Android?

MainActivity. SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text2); // It is used to set foreground color. ForegroundColorSpan green = new ForegroundColorSpan(Color. GREEN);

Can we change the text in TextView?

TextView tv1 = (TextView)findViewById(R. id. textView1); tv1. setText("Hello"); setContentView(tv1);

Can you have multiple styles inside TextView?

Use multiple widgets if you need precise placement of discrete bits of text. Use inline markup if you, um, need markup inline in a widget. Remember: there is no FlowLayout in Android, so stringing together multiple TextViews to create a paragraph is not truly practical AFAIK.


2 Answers

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

like image 158
Kaj Avatar answered Nov 08 '22 21:11

Kaj


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

like image 22
ingsaurabh Avatar answered Nov 08 '22 23:11

ingsaurabh