Android TextView文字字体颜色改变

一:TextView组件改变部分文字的颜色:

TextView textView = (TextView)findViewById(R.id.textview);  
  
//方法一:  
textView.setText(Html.fromHtml("<font color=\"#ff0000\">红色</font>其它颜色"));  
  
//方法二:  
 String text = "获得银宝箱!";  
 SpannableStringBuilder style=new SpannableStringBuilder(text);     
  style.setSpan(new BackgroundColorSpan(Color.RED),2,5,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);     //设置指定位置textview的背景颜色  
  style.setSpan(new ForegroundColorSpan(Color.RED),0,2,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);     //设置指定位置文字的颜色  
  textView.setText(style);   

二:Android string.xml文件中的整型和string型代替:

String text = String.format(getResources().getString(R.string.baoxiang), 2,18,"银宝箱");  

 对应的string.xml文件参数:

<string name="baoxiang">您今天打了%1$d局,还差%2$d局可获得%3$s!</string>  

 %1$d表达的意思是整个name=”baoxiang”字符串中,第一个整型

 

 

在项目开发者,经常需要把以上两者结合起来使用。可以避免很多textview的拼接,如下所示:

TextView textView = (TextView)findViewById(R.id.testview);  
  
String text = String.format(getResources().getString(R.string.baoxiang), 2,18,"银宝箱");  
       int index[] = new int[3];  
       index[0] = text.indexOf("2");  
       index[1] = text.indexOf("18");  
       index[2] = text.indexOf("银宝箱");  
  
 SpannableStringBuilder style=new SpannableStringBuilder(text);     
           style.setSpan(new ForegroundColorSpan(Color.RED),index[0],index[0]+1,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);      
           style.setSpan(new ForegroundColorSpan(Color.RED),index[1],index[1]+2,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);      
           style.setSpan(new BackgroundColorSpan(Color.RED),index[2],index[2]+3,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
           style.setSpan(new AbsoluteSizeSpan(30),index[0],index[1],index[1]+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);     //设置字体大小
           textView.setText(style);  

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值