android – 一次向SpannableString添加多个样式

目前,我正在使用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));

相关文章

Android 如何解决dialog弹出时无法捕捉Activity的back事件 在...
Android实现自定义带文字和图片的Button 在Android开发中经常...
Android 关于长按back键退出应用程序的实现最近在做一个Andr...
android自带的时间选择器只能精确到分,但是对于某些应用要求...