Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 932
Roman Rdgz Avatar asked Nov 12 '11 15:11

Roman Rdgz


1 Answers

Here's a little helper function based on C0deAttack's answer, that 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 to

textView.append("Text")

with

appendColoredText(textView, "Text", Color.RED);
like image 151
benjymous Avatar answered Sep 21 '22 23:09

benjymous