正如标题所说,我想知道是否有可能在单个textview元素中实现两个不同颜色的字符。


当前回答

尽可能使用SpannableBuilder类而不是HTML格式,因为它比HTML格式解析更快。 在Github上查看我自己的基准测试“SpannableBuilder vs HTML” 谢谢!

其他回答

使用Kotlin和扩展,您可以添加彩色文本非常简单和干净:

创建一个TextViewExtensions文件。Kt和这个含量

fun TextView.append(string: String?, @ColorRes color: Int) {
    if (string == null || string.isEmpty()) {
        return
    }

    val spannable: Spannable = SpannableString(string)
    spannable.setSpan(
        ForegroundColorSpan(ContextCompat.getColor(context, color)),
        0,
        spannable.length,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
    )

    append(spannable)
}

现在很容易添加文本的颜色

textView.text = "" // Remove old text
textView.append("Red Text", R.color.colorAccent)
textView.append("White Text", android.R.color.white)

基本上与@Abdul Rizwan的答案相同,但使用Kotlin,扩展,一些验证和在扩展内部获得颜色。

是的,如果你用html的font-color属性格式化字符串,然后把它传递给方法html . fromhtml(你的文本在这里)

String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));

你可以在没有HTML的情况下打印多种颜色的行:

TextView textView = (TextView) findViewById(R.id.mytextview01);
Spannable word = new SpannableString("Your message");        

word.setSpan(new ForegroundColorSpan(Color.BLUE), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

textView.setText(word);
Spannable wordTwo = new SpannableString("Your new message");        

wordTwo.setSpan(new ForegroundColorSpan(Color.RED), 0, wordTwo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(wordTwo);

我不知道,因为这是可能的,但你可以简单地添加<font> </font>到你的string.xml,这将自动改变每个文本的颜色。不需要添加任何额外的代码,如可扩展的文本等。

例子

<string name="my_formatted_text">
    <font color="#FF0707">THIS IS RED</font>
    <font color="#0B132B">AND NOW BLUE</font>
</string>

使用SpannableStringBuilder

SpannableStringBuilder builder = new SpannableStringBuilder();

SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);

SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);
builder.append(str2);

TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);