1. 程式人生 > >android textview改變一部分文字的顏色和string.xml中文字的替換

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

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

一:TextView元件改變部分文字的顏色:
TextView textView = (TextView)findViewById(R.id.textview);
//方法一:
textView.setText(Html.fromHtml(“紅色其它顏色”));
//方法二:
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檔案引數:
這裡寫圖片描述
%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);