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

項目中做國際化UI的調整,因爲中文和英文不一樣,所以,用到了這裏的知識:
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的拼接,如下所示:

 

Java代碼  收藏代碼
  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.            textView.setText(style);  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章