安卓TextView中改变部分文字颜色的几种方式


1. 第一种使用SpannableStringBuilder 
//部分文字改变颜色  
//ForegroundColorSpan 为文字前景色,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); 

2. 第二种,使用Html.fromHtml()

TextView desc1 = (TextView)findViewById(R.id.desc1);
TextView desc2 = (TextView)findViewById(R.id.desc2);
TextView desc3 = (TextView)findViewById(R.id.desc3);
String content1 = "务必使用<font color='red'>银行卡</font>开户时<font color='red'>预留手机号</font>!";
String content2 = "点击获取验证码按钮后,您将收到<font color='red'>银行验证码短信</font>!";
String content3 = "时间<font color='red'>工作日09:00 - 次日06:00</font>!";
desc1.setText(Html.fromHtml(content1));
desc2.setText(Html.fromHtml(content2));
desc3.setText(Html.fromHtml(content3));

3. 总结

1. 使用SpannableStringBuilder由于颜色是在本地定义的,所以可以精确地控制要显示的颜色,兼容性最好。

缺点也很明显太麻烦了,需要为每一种颜色定义一个ForegroundColorSpan 

2. 使用Html方式则相对比较简单,直接在字符串里面使用标签即可,但是缺点也相对明显,只能使用标签里面预定义的集中颜色值,与本地兼容性不是很好

4. 若还有其他方式欢迎指出

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值