1、设置textview的前景色和背景色
String str=
"这是设置TextView部分文字背景颜色和前景颜色的demo!"
;
int
bstart=str.indexOf(
"背景"
);
int
bend=bstart+
"背景"
.length();
int
fstart=str.indexOf(
"前景"
);
int
fend=fstart+
"前景"
.length();
SpannableStringBuilder style=
new
SpannableStringBuilder(str);
style.setSpan(
new
BackgroundColorSpan(Color.RED),bstart,bend,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(
new
ForegroundColorSpan(Color.RED),fstart,fend,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
TextView tvColor=(TextView) findViewById(R.id.tv_color);
tvColor.setText(style);
2、设置字体大小
String message="textview字体的大小,我是12字体";
SpannableString styledText = new SpannableString(message);
styledText.setSpan(new TextAppearanceSpan(this, R.style.TextSize20), 0, message.indexOf(","), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
styledText.setSpan(new TextAppearanceSpan(this, R.style.TextSize12), message.indexOf(",")+1, message.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(styledText, TextView.BufferType.SPANNABLE);
3.同一个textview设置不同的颜色
String message;
ForegroundColorSpan yellowSpan = new ForegroundColorSpan(0xffD2691E);
SpannableStringBuilder style=new SpannableStringBuilder();
message="我是第一种颜色,我是第二种颜色";
style.append(message);
style.setSpan(yellowSpan, 0, message.indexOf(",")+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ForegroundColorSpan orangeSpan = new ForegroundColorSpan(0xffFF6600);
style.setSpan(orangeSpan, message.indexOf(",")+1, message.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(style);