Android - TextView with different background colors

Is it possible to have a TextView with different background colors. For example. If the text is "This is a test", can the background be set to four background colors?

+3


source to share


1 answer


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

      

Outputs:



enter image description here

EDIT: There are many different types of spunning, you can do much nicer things than my main example. Check out this article.

+11


source







All Articles