Is it possible to have a TextView with different background colors. Eg. If the text is "This is a test", is it possible to set different background color for the four words?
Asked
Active
Viewed 2,570 times
3
-
You mean in the same TextView with different background colors? – CodeCanyon Sep 29 '14 at 03:44
-
can you give an example of what you mean? – Amulya Khare Sep 29 '14 at 03:45
-
yes. That is what I want to do. – user2260040 Sep 29 '14 at 03:45
-
You could have 4 textviews with different backgrounds and each containing a word and connect them together... – nem035 Sep 29 '14 at 03:55
-
Here is an example of what I want to do... http://tinypic.com/r/15oeyp3/8 The right hand side of the image has text with different backgrounds. The text is dynamic so I can't go with the fixed number of textviews. – user2260040 Sep 29 '14 at 03:55
-
Simply use SpannableString as mentioned in below ans post. – Haresh Chhelana Sep 29 '14 at 04:28
1 Answers
13
Yes.
SpannableString spannableString = new SpannableString(getString(R.string.hello_world));
Object greenSpan = new BackgroundColorSpan(Color.GREEN);
Object redSpan = new BackgroundColorSpan(Color.RED);
spannableString.setSpan(greenSpan, 0, 6, 0);
spannableString.setSpan(redSpan, 6, spannableString.length(), 0);
TextView textView = (TextView) findViewById(R.id.text);
textView.setText(spannableString);
Produces:
EDIT: There are a lot of different spannable types, you can do much nicer looking things than my basic example. Check out this article.

Bradley Campbell
- 9,298
- 6
- 37
- 47