Android multi color in one TextView

Hüseyin Zeki picture Hüseyin Zeki · Apr 13, 2012 · Viewed 55.6k times · Source

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?

Answer

Costi Muraru picture Costi Muraru · Apr 13, 2012

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);
}