1. 程式人生 > >Android一個TextView設定多種顏色的2種高效方法

Android一個TextView設定多種顏色的2種高效方法

有時候一個文字框為了強調內容需要顯示不同顏色,用以下程式碼可以輕鬆實現

方法一:(適用於顏色變化多的情況)

 //為文字框設定多種顏色
	textView=(TextView)findViewById(R.id.text_show);
        SpannableStringBuilder style = new SpannableStringBuilder("備註:簽收人(張三)");
        style.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.setSpan(new ForegroundColorSpan(Color.RED), 7, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(style);


方法二:(高校,快捷)

首先在字串中就設定好顏色屬性

String str1=String.format("價格 :<font color=\"#d40000\">%s", String.format("¥%1$.2f元", item.getPrice()));
String str2=String.format("狀態 :<font color=\"#666666\">%s", "已售");
然後用Html.fromHtml()方法
mStaringPriceTV.setText(Html.fromHtml(str1));
mCountdownTimeTV.setText(Html.fromHtml(str2));

像這種情況用一個文字框來實現會很省事