mark16
mark16

Reputation: 25

How to change color of individual letters in textView?

I am displaying text in android like this:

TextView textview p new TextView(this);
textview.setMovementMethod(new ScrollingMethod());
textview.setText("Today: 2\nTomorrow: 8\nNext two weeks: 45");
textview.setTextSize(16);
textview.setTypeFace(null, TypeFace.BOLD);
setContentView(textview);

I want to make the 2, 8 and 45 from the text green while leaving the rest black. I know how to do it for all the text but not individual characters. Can someone help? I have looked through other similar questions but none seem to be setting the textview the way I am here.

Upvotes: 1

Views: 2263

Answers (2)

Programmer
Programmer

Reputation: 878

You can try this :

TextView textview p new TextView(this);
textview.setMovementMethod(new ScrollingMethod());
    textview.setText(Html.fromHtml("Today: <font color=green>2</font>\nTomorrow: <font color=green>8</font>\nNext two weeks: <font color=green>45</font>");
textview.setTextSize(16);
textview.setTypeFace(null, TypeFace.BOLD);
setContentView(textview);

This will set green colors to 2,8,45. simillarly you can use any html tags for textview text. Hope this will help you.

Upvotes: 2

Karakuri
Karakuri

Reputation: 38605

Use SpannableString and add ForegroundColorSpans to the text. You'll have to find the indexes of the charactes/substrings that you want to be spanned so you can call addSpan

SpannableString spannedText = new SpannableString(originalText);
int start = ..., end = ...;
spannedText.addSpan(new ForegroundColorSpan(Color.GREEN), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

Upvotes: 9

Related Questions