Search code examples
androidcolorstextview

Can I select a color for each text line I append to a 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?

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.


Solution

  • 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?

    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.