安卓TextView部分字体改变颜色以及背景

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010023795/article/details/54951127

> 1. 第一种使用SpannableStringBuilder和 BackgroundColorSpan

//首先给赋值颜色
ForegroundColorSpan redSpan = new ForegroundColorSpan(getResources().getColor(R.color.text_red));
ForegroundColorSpan graySpan = new ForegroundColorSpan(getResources().getColor(R.color.text_gray));
mTextView.setText(“灰色红色”);
//这里注意一定要先给textview赋值
SpannableStringBuilder builder = new SpannableStringBuilder(mTextView.getText().toString());
//为不同位置字符串设置不同颜色
//四个参数分别为,颜色值,起始位置,结束位置,最后的为类型。
builder.setSpan(graySpan, 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(redSpan, 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//最后为textview赋值
mTextView.setText(builder);

 String str="设置TextView部分字体颜色以及背景颜色!";
        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);


补充:
AbsoluteSizeSpan(int size) ---- 设置字体大小,参数是绝对数值,相当于Word中的字体大小
RelativeSizeSpan(float proportion) ---- 设置字体大小,参数是相对于默认字体大小的倍数,比如默认字体大小是x, 那么设置后的字体大小就是x*proportion,这个用起来比较灵活,proportion>1就是放大(zoom in), proportion<1就是缩小(zoom out)
ScaleXSpan(float proportion) ---- 缩放字体,与上面的类似,默认为1,设置后就是原来的乘以proportion,大于1时放大(zoon in),小于时缩小(zoom out)
BackgroundColorSpan(int color) ----背景着色,参数是颜色数值,可以直接使用android.graphics.Color里面定义的常量,或是用Color.rgb(int, int, int)
ForegroundColorSpan(int color) ----前景着色,也就是字的着色,参数与背景着色一致TypefaceSpan(String family) ----字体,参数是字体的名字比如“sans", "sans-serif"等
StyleSpan(Typeface style) -----字体风格,比如粗体,斜体,参数是android.graphics.Typeface里面定义的常量,如Typeface.BOLD,Typeface.ITALIC等等。StrikethroughSpan----如果设置了此风格,会有一条线从中间穿过所有的字,就像被划掉一样

> 1. 第二种使用使用Html.fromHtml()

TextView tv= (TextView)findViewById(R.id.desc1);
String content = "更改部分字体<font color='red'>的字体颜色</font>使用Html<font color='red'>或者SpannableStringBuilder</font>!";
tv.setText(Html.fromHtml(content));

参考:http://www.2cto.com/kf/201409/335648.html

http://www.cnblogs.com/kingsam/p/5643598.html

猜你喜欢

转载自blog.csdn.net/u010023795/article/details/54951127
今日推荐