1

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.

mark16
  • 25
  • 1
  • 1
  • 4
  • Check out this one: http://stackoverflow.com/questions/10392163/using-multiple-text-colors-in-androids-textview-html-fromhtml – Synx Oct 01 '14 at 15:26
  • how can i use this if not using html to get the text but just have it commented in? – mark16 Oct 01 '14 at 15:28

2 Answers2

9

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);
Karakuri
  • 38,365
  • 12
  • 84
  • 104
2

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.

Programmer
  • 878
  • 2
  • 11
  • 24