Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - TextView with different background colors

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?

like image 814
user2260040 Avatar asked May 31 '26 01:05

user2260040


1 Answers

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.

like image 60
Bradley Campbell Avatar answered Jun 01 '26 16:06

Bradley Campbell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!