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

來源:互聯網
上載者:User

項目中做國際化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);  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.