TextView組件改變部分文字的顏色和多字符串拼接

原文:http://www.cnblogs.com/bill-joy/archive/2012/03/24/2415539.html
 
一: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文件參數:
 
<</SPAN>string name="baoxiang">您今天打了%1$d局,還差%2$d局可獲得%3$s!</</SPAN>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); 
textView.setText(style);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章