我可以为TextView追加的每一行文本选择不同的颜色吗?

6

我有一个TextView用作蓝牙连接控制台。当我发送命令时,我希望它以一种颜色(例如青色)书写,并以另一种颜色(例如红色)接收到的回答。

这是可能的吗?如果可以,怎么做呢?

我读到可以使用HTML来实现,但我不确定它是否是最佳方法,甚至如何实现。


请查看https://dev59.com/bWAg5IYBdhLWcg3w_vOE#30096905。 - qw1nz
5个回答

18

这是一个基于C0deAttack答案的小帮助函数,可以简化事情

public static void appendColoredText(TextView tv, String text, int color) {
    int start = tv.getText().length();
    tv.append(text);
    int end = tv.getText().length();

    Spannable spannableText = (Spannable) tv.getText();
    spannableText.setSpan(new ForegroundColorSpan(color), start, end, 0);
}

只需将任何调用

textView.append("Text")

使用

appendColoredText(textView, "Text", Color.RED);

请问您能否解释一下,如果传递一个预构建的ForegroundColorSpan对象而不是颜色参数,为什么这个解决方案不再起作用了呢?谢谢。 - MadBlack

8

你真的需要它是一个TextView吗?或者你可以使用ListView,为每个命令/答案添加新行到列表中。

如果你确实想使用TextView,你可以像这样做(这是一个工作示例,你可以直接复制粘贴到你的应用程序中尝试):

package com.c0deattack;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.style.ForegroundColorSpan;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MultipleColoursInOneTextViewActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView tv = new TextView(this);

        String command = "This is a command";
        String response = "\nThis is a response";

        tv.append(command + response);
        Spannable spannableText = (Spannable) tv.getText();
        spannableText.setSpan(new ForegroundColorSpan(Color.GREEN), 0, command.length(), 0);
        spannableText.setSpan(new ForegroundColorSpan(Color.RED), command.length(), command.length() + response.length(), 0);

        LinearLayout layout = new LinearLayout(this);
        layout.addView(tv);
        setContentView(layout);
    }
}

那表明这是可以实现的,但你显然会注意到你需要自己设置换行,并确定每个指令/答案的起始和结束位置,以便为其应用正确的颜色。虽然不是很难,但在我看来感觉有些笨拙。


我想使用TextView,因为它看起来像控制台终端。ListView在每两行之间有水平线,所以看起来不太一样。如果您知道如何避免这些线条,那么对我来说可能也奏效。如果您知道如何,请解释一下。 - Roman Rdgz

0
public static void appendColoredText(TextView tv, String text, int color) {
    SpannableStringBuilder ssb = new SpannableStringBuilder();
    ssb.append(text);
    ssb.setSpan(new ForegroundColorSpan(color), 0, text.length(), 0);
    tv.append(ssb);
}

优化@benjymous的答案

我们可以创建一个SpannableStringBuilder对象来保存textcolor span,并使用它的append()setSpan()方法来添加文本和颜色span。

这样会更有效率,因为它避免了每次调用该方法时都创建一个新的Spannable对象。


0

如果你使用以下工具,会更容易:

textView.append(Html.fromHtml("<font color='#FFFFFF'</font>"));

-3
检查每个状态 textView.setTextColor(Color.RED);

这会不会改变所有的书面文本,包括发送和接收的文本,都变成我给定的颜色? - Roman Rdgz
1
我认为也是这样。这个解决方案一点也不令人满意。 - AsTeR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接