3

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?

user2260040
  • 1,275
  • 1
  • 13
  • 26

1 Answers1

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:

enter image description here

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