我正在尝试使用SpannableStringBuilder
来构建包含不同样式的文本。但是在追加更多字符串之后风格就会丢失。
public SpannableStringBuilder buildMixStyleText() {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
TextAppearanceSpan styleRed = new TextAppearanceSpan(getBaseContext(), R.style.Red);
TextAppearanceSpan styleGreen = new TextAppearanceSpan(getBaseContext(), R.style.Green);
for (int i = 0; i < 10; i++) {
SpannableString red = new SpannableString("red");
red.setSpan(styleRed, 0, red.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.append(red);
spannableStringBuilder.append("\n");
SpannableString green = new SpannableString("green");
green.setSpan(styleGreen, 0, green.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.append(green);
spannableStringBuilder.append("\n");
}
return spannableStringBuilder;
}
Textview显示前两次红色为“红色”,绿色为“绿色”,下一次失去样式,它们都是灰色的默认颜色。
答案 0 :(得分:1)
尝试替换styleGreen
中的green.setSpan(styleGreen, 0, green.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
;与new TextAppearanceSpan(getBaseContext(), R.style.Green)