一次向SpannableString添加多个样式

8

目前,我正在使用SpannableString为字符串的一部分设置文本和背景颜色,如下所示:

SpannableStringBuilder spanString = new SpannableStringBuilder(text);
spanString.setSpan( new ForegroundColorSpan(Color.RED), start, end, 0 );
spanString.setSpan( new BackgroundColorSpan(Color.GRAY), start, end, 0 );

有没有一种方法将这两种样式合并到一个CharacterStyle对象中,并以一个命令设置为文本?
1个回答

8
如果您最终想要设置TextView(或类似的东西)的文本,您可以使用SpannableString来单独格式化每个字符串,并使用TextUtils.concat将它们拼接在一起,这样就不需要SpannableStringBuilder
下面的代码将TextView中的文本设置为“Hello World”,其中“Hello”是红色的,“World”是绿色的。
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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接