目前,我正在使用SpannableString为字符串的一部分设置文本和背景颜色,如下所示:
- SpannableStringBuilder spanString = new SpannableStringBuilder(text);
- spanString.setSpan( new ForegroundColorSpan(Color.RED),start,end,0 );
- spanString.setSpan( new BackgroundColorSpan(Color.GRAY),0 );
有没有办法将这两种样式组合成一个CharacterStyle对象并在一个命令中将其设置为文本?
解决方法
如果您最终想要设置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),myStr1.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
- myStr2.setSpan( new ForegroundColorSpan(Color.GREEN),myStr2.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
- myTextView.setText(TextUtils.concat(myStr1," ",myStr2));