android textview改變部分文字的顏色和string.xml中文字的替換(轉)


轉   :http://blog.csdn.net/ljz2009y/article/details/23878669

一:TextView組件改變部分文字的顏色:

 

Java代碼   收藏代碼
  1. TextView textView = (TextView)findViewById(R.id.textview);  
  2.   
  3. //方法一:  
  4. textView.setText(Html.fromHtml("<font color=\"#ff0000\">紅色</font>其它顏色"));  
  5.   
  6. //方法二:  
  7.  String text = "獲得銀寶箱!";  
  8.  SpannableStringBuilder style=new SpannableStringBuilder(text);     
  9.   style.setSpan(new BackgroundColorSpan(Color.RED),2,5,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);     //設置指定位置textview的背景顏色  
  10.   style.setSpan(new ForegroundColorSpan(Color.RED),0,2,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);     //設置指定位置文字的顏色  
  11.   textView.setText(style);   

 

 

 

 

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

 

Java代碼   收藏代碼
  1. String text = String.format(getResources().getString(R.string.baoxiang), 2,18,"銀寶箱");  

 

 對應的string.xml文件參數:

 

Xml代碼   收藏代碼
  1. <string name="baoxiang">您今天打了%1$d局,還差%2$d局可獲得%3$s!</string>  

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

 

 

在項目開發者,經常需要把以上兩者結合起來使用。可以避免很多textview的拼接,如下所示:

 

 

  1. TextView textView = (TextView)findViewById(R.id.testview);  
  2.   
  3. String text = String.format(getResources().getString(R.string.baoxiang), 2,18,"銀寶箱");  
  4.        int index[] = new int[3];  
  5.        index[0] = text.indexOf("2");  
  6.        index[1] = text.indexOf("18");  
  7.        index[2] = text.indexOf("銀寶箱");  
  8.   
  9.  SpannableStringBuilder style=new SpannableStringBuilder(text);     
  10.            style.setSpan(new ForegroundColorSpan(Color.RED),index[0],index[0]+1,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);      
  11.            style.setSpan(new ForegroundColorSpan(Color.RED),index[1],index[1]+2,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);      
  12.            style.setSpan(new BackgroundColorSpan(Color.RED),index[2],index[2]+3,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
  13.            style.setSpan(new AbsoluteSizeSpan(30),index[0],index[1],index[1]+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);     //設置字體大小
  14.            textView.setText(style);  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM