gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:07:17 28 4
gpt4 key购买 nike

目前,我正在使用 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 对象中,并在一个命令中将其设置为文本?

最佳答案

如果您最终想要设置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), 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));

关于android - 一次向 SpannableString 添加多个样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8915109/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com