我可以为每个文本行我附加到一个TextView颜色?

编程入门 行业动态 更新时间:2024-10-06 18:34:55
本文介绍了我可以为每个文本行我附加到一个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颜色?

本文发布于:2023-11-02 06:23:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551611.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我可   文本   颜色   TextView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!