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性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...