59

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?

Community
  • 1
  • 1
Hüseyin Z.
  • 836
  • 1
  • 8
  • 18
  • I have create some library for it. feel free to take a look and post an issues on it if you find some issues https://github.com/ha-yi/MultiColorTextView – Hayi Nukman Aug 17 '19 at 12:42
  • I dont understand your github collection –  Aug 18 '19 at 23:35

3 Answers3

100

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);
}
Roman Smoliar
  • 1,093
  • 13
  • 15
Costi Muraru
  • 2,065
  • 1
  • 20
  • 25
  • can we similarly set the background of a part of the text? – Viral Patel Feb 11 '16 at 06:27
  • 2
    You can also put this string in strings.xml (but you have to surround it with `<![CDATA[**Your string here**]]>`). Then you set the string like what he said, but you don't need TextView.BufferType.SPANNABLE for it. – Daniel Handojo Aug 30 '16 at 16:51
92

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);
NitroG42
  • 5,336
  • 2
  • 28
  • 32
Khan
  • 7,585
  • 3
  • 27
  • 44
  • 1
    OP already said he doesn't know how many words will be in the text, which rules out any sort of solution using hard-coded positions. – tbm May 08 '14 at 21:54
  • 1
    @tbm I have just suggested a simple solution and based on it we can make a dynamic too like from sentence "Hi" word should be shown in red color "Bye" word in blue color and so on and for this we have to get dynamic position and than we can add our logic based on it. – Khan May 09 '14 at 04:30
  • 4
    @tbm then don't hard code them, calculate them on the fly. I like this answer. – Bernard Igiri Nov 11 '14 at 23:27
  • 2
    This is a better - and less resource-intensive - solution than the accepted answer. It does not require unnecessary parsing of text. – Melllvar Aug 22 '17 at 18:22
7

What you basically want is SpannableString

See this for the complete example:

Arif Nadeem
  • 8,524
  • 7
  • 47
  • 78