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);
您可能可以使用这样的函数(使用 spannable)来更改每个单词的颜色
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;
}
更简单的方法:
TextView.setText(Html.fromHtml("<some html color tag/>"));
您可以使用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);
您可以按空格拆分单词并将跨度设置为单词。
例子 :
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++;
}
快照