Can I select a color for each text line that I add to a TextView?

I have a TextView that will be used as a Bluetooth connection console. When I send a command, I want it to be written in color (for example, blue), and the responses received in a different color (for example, red).

Can this be done, and if so, how?

I read that this is possible using HTML, but I'm not quite sure if this is the best approach or even how to do it.

+4
source share
4 answers

Do you really need it to be a TextView or can you use a ListView instead and add a new row to the list for each command / response?

If you really want to use TextView, you can do something like this (this is a working example that you can just copy and paste into your application to try it):

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 this shows that this can be done, but you will obviously notice that you will need to set line breaks and workouts where each team / answer starts and ends so that you can apply the correct color to it. It is not so difficult, but for me it is inconvenient.

+7
source

Here's a little helper function based on C0deAttack's answer, which simplifies things

 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); } 

Just replace any calls with

 textView.append("Text") 

with

 appendColoredText(textView, "Text", Color.RED); 
+16
source

This is easier if you use:

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

check for each state textView.setTextColor (Color.RED);

-3
source

Source: https://habr.com/ru/post/1380914/


All Articles