Android multi color in one TextView

AndroidTextviewStyling

Android Problem Overview


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

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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

Solution 3 - Android

What you basically want is SpannableString

See this for the complete example:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionH&#252;seyin ZekiView Question on Stackoverflow
Solution 1 - AndroidCosti MuraruView Answer on Stackoverflow
Solution 2 - AndroidKhanView Answer on Stackoverflow
Solution 3 - AndroidArif NadeemView Answer on Stackoverflow