我可以为每个文本行我附加到一个TextView颜色? [英] Can I select a color for each text line I append to a TextView?
问题描述
我有一个TextView被用作蓝牙连接控制台。当我发送一个命令,我希望它被写在一个颜色(例如青色),并以不同的颜色接收(例如红色)的答案。
I have a TextView to be used as a bluetooth connection console. When I send a command, I want it to be written in a color (for example cyan), and the answers received in a different color (for example red).
是否有可能做到这一点,如果是的话,怎么办?
Is it possible to do that, and if so, how?
我读它可能会使用HTML做的,但我不能肯定这是最好的方法,甚至是如何做到这一点。
I read it may be possible to do using HTML, but i'm not quite sure it is the best approach, or even how to do it.
推荐答案
你真的需要它是一个TextView,也可以使用一个ListView来代替,并在列表中添加一个新行的每一个命令/回答?
Do you really need it to be a TextView or can you use a ListView instead and add a new row in the list for each command/answer?
如果您的真正的想用一个TextView,你可以做这样的事情(这是你可以复制并粘贴到你的应用程序尝试的工作示例):
If you really want to use a TextView you can do something like this (This is a working example you can just copy and paste to your app to try out):
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);
}
}
所以这表明,这是可以做到的,但你会明显地发现,你必须设置换行符自己,锻炼,每个命令/响应的开始和结束,因此您可以应用正确的颜色吧。这并不难,但对我来说,感觉笨拙。
So that shows that it can be done, but you'll obviously notice you'll have to set the line breaks yourself and workout where each command/answer starts and ends so you can apply the correct colour to it. It's not that hard but to me, feels clunky.
这篇关于我可以为每个文本行我附加到一个TextView颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!