標籤:spannable spannablestringbuild android textview 字型顏色
在這裡先看看:
OK,有時候,在我們的項目中會要求TextView中文本有一部分的字型顏色不一樣,這時我們應該使用
SpannableStringBuilder這個工具類,當然這個類的功能很強大,這裡我只是實現上面的樣式,其它的不做介紹,
SpannableStringBuilder的實現介面是Spannable這個介面,而Spannable最終都實現了CharSequence,因此我們直
接可以通過TextView.setText()來進行設定。
下面給出實現代碼:
public class StringFormatUtil {private SpannableStringBuilder spBuilder;private String wholeStr, highlightStr;private Context mContext;private int color;private int start = 0, end = 0;/** * * @param context * @param wholeStr 全部文字 * @param highlightStr 改變顏色的文字 * @param color 顏色 */public StringFormatUtil(Context context,String wholeStr,String highlightStr,int color){this.mContext=context;this.wholeStr=wholeStr;this.highlightStr=highlightStr;this.color=color;}public StringFormatUtil fillColor(){if(!TextUtils.isEmpty(wholeStr)&&!TextUtils.isEmpty(highlightStr)){if(wholeStr.contains(highlightStr)){/* * 返回highlightStr字串wholeStr字串中第一次出現處的索引。 */start=wholeStr.indexOf(highlightStr);end=start+highlightStr.length();}else{return null;}}else{return null;}spBuilder=new SpannableStringBuilder(wholeStr);color=mContext.getResources().getColor(color);CharacterStyle charaStyle=new ForegroundColorSpan(color);spBuilder.setSpan(charaStyle, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);return this;}public SpannableStringBuilder getResult(){if (spBuilder != null) {return spBuilder;}return null;}}
當然上面的第一步是擷取你要改變顏色的文字的起始位置到結束位置,接著通過SpannableStringBuilder來改變文字
的顏色。
public class MainActivity extends Activity {private TextView tv_show;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();}private void initView() {tv_show = (TextView) findViewById(R.id.tv_show);String wholeStr = "想要改變後面的顏色這是要改變的顏色";StringFormatUtil spanStr = new StringFormatUtil(this, wholeStr,"這是要改變的顏色", R.color.blue).fillColor();tv_show.setText(spanStr.getResult());}}
轉載請註明出處:http://blog.csdn.net/hai_qing_xu_kong/article/details/44225955 情緒控_
一起學android之如何設定TextView中不同欄位的字型顏色(22)