2012-01-18 33 views
8

目前,我正在使用SpannableString像这样设置文本和背景颜色为字符串的一部分:一次添加多个样式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对象并将其设置为一个命令中的文本?

回答

8

如果你最终想要设置的TextView(或类似的东西),你可以使用SpannableString每串分别格式化并使用TextUtils.concat修补他们在一起,这消除了对SpannableStringBuilder需要的文本。

下面的代码设置文本在TextView为“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));