一次添加多个样式SpannableString [英] Add multiple styles at once to SpannableString
问题描述
目前,我正在使用SpannableString像这样设置文字和背景颜色为字符串的一部分:
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 );
有没有什么办法这两方面的风格组合成一个CharacterStyle对象,并将它设置在一个命令文本?
Is there any way to combine both of those styles into one CharacterStyle object and set it to text in one command?
推荐答案
如果你最终想要设置的的TextView
(或类似的东西),你可以使用文本 SpannableString
来分别格式化每个字符串,并使用 TextUtils.concat
来修补他们在一起,从而无需为 SpannableStringBuilder
。
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
.
下面将的TextView
文本中的code为Hello World,其中你好是红色的世界是绿色的。
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));
这篇关于一次添加多个样式SpannableString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!