views:

200

answers:

2

Is it possible to set the color of just span of text in a TextView?

I would like to do something similar to the Twitter app, in which a part of the text is blue. See image below:

alt text

Thanks!

+2  A: 

set your TtextView´s text spannable and define a ForegroundColorSpanfor your text.

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

TV.setText("I know just how to whisper, And I know just how to cry,I know just where to find the answers", TV.BufferType.SPANNABLE);

Spannable WordtoSpan = (Spannable) myTextView.getText();        

WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TV.setText(WordtoSpan);
Jorgesys
Thanks! Is it possible to do this without assigning the text to the TextView first?
hgpc
I didn't explain myself well. Let me rephrase. Are the first 3 lines necessary? Can't you create the Spannable object from the string directly?
hgpc
Nop, you have to store your TextView's text into a Buffer Spannable to change the foreground colour.
Jorgesys
+1  A: 

Another answer would be very similar, but wouldn't need to set the text of the TextView twice

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

Spannable WordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");        

WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TV.setText(WordtoSpan);
Daniel
Clearer code. Thanks!
hgpc