Currently, I'm setting text and background colors for a part of string using SpannableString like so:
SpannableStringBuilder spanString = new SpannableStringBuilder(text);
spanString.setSpan( new ForegroundColorSpan(Color.RED), start, end, 0 );
spanString.setSpan( new BackgroundColorSpan(Color.GRAY), start, end, 0 );
Is there any way to combine both of those styles into one CharacterStyle object and set it to text in one command?
There are many ways to make multiple styles inside android TextView and in this example I have made multiple style with three different ways using HTML tags and Html. fromHtml().
Text styling is one of the important aspects when it comes to enhancing the UI of an Android application. In Android, we can change the size, color, weight, style, etc of a text and make the text more attractive and appealing.
Spanned -> immutable text with immutable markup. Spannable (extends Spanned )-> immutable text with mutable markup. Apply a span by calling setSpan(Object what, int start, int end, int flags) on the Spannable object. The what Object is the marker that will be applied from a start to an end index in the text.
If you ultimately want to set the text of a TextView
(or something similar), you can use SpannableString
to format each string separately and use TextUtils.concat
to patch them together, which removes the need for a SpannableStringBuilder
.
The code below set the text in the TextView
to "Hello World" where "Hello" is red and "World" is green.
TextView myTextView = new TextView(this);
SpannableString myStr1 = new SpannableString("Hello");
SpannableString myStr2 = new SpannableString("World");
myStr1.setSpan( new ForegroundColorSpan(Color.RED), 0, myStr1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
myStr2.setSpan( new ForegroundColorSpan(Color.GREEN), 0, myStr2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
myTextView.setText(TextUtils.concat(myStr1, " ", myStr2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With