Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android multi color in one TextView [duplicate]

Possible Duplicate:
Is it possible to have multiple styles inside a TextView?

I want my TextView to show some part of its text in red and others in black. It's content (the text) is created dynamically and i don't know how many words will be red colored.

Is there any way to do this like in html-css?

like image 566
Hüseyin Zeki Avatar asked Apr 13 '12 12:04

Hüseyin Zeki


2 Answers

You can use Spannable to achieve what you want.

String text = "This is <font color='red'>red</font>. This is <font color='blue'>blue</font>.";

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
   textView.setText(Html.fromHtml(text,  Html.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE);
} else {
   textView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);
}
like image 194
Costi Muraru Avatar answered Nov 15 '22 01:11

Costi Muraru


try this way

    TextView tv = (TextView)findViewById(R.id.tv);

    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);
    wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 5, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    tv.setText(wordtoSpan);
like image 92
Khan Avatar answered Nov 15 '22 03:11

Khan