android 修改TextView中部分文字的颜色

来源:互联网 发布:电脑软件搬家 编辑:程序博客网 时间:2024/05/21 14:52

今天遇到有个需求,textveiw里面部分字体颜色需要改变,

借鉴的网址:

http://www.jianshu.com/p/a153ef5905ec

第一种


SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString());    //ForegroundColorSpan 为文字前景色,BackgroundColorSpan为文字背景色  ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);  ForegroundColorSpan whiteSpan = new ForegroundColorSpan(Color.WHITE);  ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.BLUE);  ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.GREEN);  ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.YELLOW);        builder.setSpan(redSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  builder.setSpan(whiteSpan, 1, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);  builder.setSpan(blueSpan, 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  builder.setSpan(greenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  builder.setSpan(yellowSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);    textView.setText(builder);  
解释:

后面

四个参数

Object what: 设置的span类型,颜色,粗体,下划线等等

int start: 开始作用的索引,包括start,索引从0开始

int end: span结束作用的索引,不包括end

int flags: 有四个取值,分别表示是否作用于span范围前后新增的字符

Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,前后都不作用

Spannable.SPAN_EXCLUSIVE_INCLUSIVE,后面作用

Spannable.SPAN_INCLUSIVE_EXCLUSIVE,前面作用

Spannable.SPAN_INCLUSIVE_INCLUSIVE,前后都作用

可以这样区分,SPAN之后第一个字母是前,第二个字母是后,EXCLUSIVE不包括,INCLUSIVE包括.


第二种

通过网页形式:

String str = "这是"+"<font color = "#3f51b5">"+"改变的颜色"+"</font>";

tv.settxt(Html.fromHtml(str));




原创粉丝点击