-1

I'd like to change the color of every word in the changing text. How can I do this?

selected.setText( "ID".Color.RED + "data".Color.BLUE);
Beryllium
  • 12,808
  • 10
  • 56
  • 86
meklod400
  • 129
  • 1
  • 2
  • 12

3 Answers3

1

You can probably use a function(that uses spannable) like this to change the color of each word

public Spannable getColoredStringSpannable(String text, int color,
        int from, int to) {

    Spannable WordtoSpan = new SpannableString(text);
    WordtoSpan.setSpan(new ForegroundColorSpan(color), from, to,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    return WordtoSpan;
}
Chetna
  • 864
  • 8
  • 26
0

You can use SpannableString

SpannableString ss1=  new SpannableString("ID"); 
ss1.setSpan(new ForegroundColorSpan(Color.RED), 0, ss1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
selected.append(ss1);
SpannableString ss2=  new SpannableString("data"); 
ss2.setSpan(new ForegroundColorSpan(Color.BLUE), 0, ss2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
selected.append(ss2);

You can split the words by space and set the span to words.

Example :

TextView _tv = (TextView) findViewById( R.id.tv );
int[] color ={Color.BLUE,Color.RED,Color.GREEN};
String s =" My Dynamic Text"; 
String split[] = s.split("\\s");
int j=0;
for(int i=1;i<split.length;i++)
{
    System.out.println(split[i]);
    SpannableString ss2=  new SpannableString(split[i]);     
    ss2.setSpan(new ForegroundColorSpan(color[j]), 0, ss2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    _tv.append(ss2);
    _tv.append(" ");
    j++;
}

Snap shot

enter image description here

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

More simple way:

TextView.setText(Html.fromHtml("<some html color tag/>"));
RRTW
  • 3,160
  • 1
  • 35
  • 54