关键词
Android 、TextView、多种颜色
摘要
由于项目开发需要,一个 TextView 为了强调内容,需要显示不同的字体颜色和大小
效果图
方法一
int totalCount = 3;
double totalPrice = 33.8;
String str = "共<font color='#ff0000'> " + totalCount + " </font>件商品,"
+ "已付款<font color='#ff0000'> ¥" + String.format("%.2f", totalPrice) + " </font>元";
Spanned content = Html.fromHtml(str);
mTextView.setText (content);
注意:不能将包含 Html 标签的字符串放到 strings.xml
方法二
int totalCount = 3;
double totalPrice = 33.8;
String totalCountStr = totalCount +"";
String totalPriceStr = String.format("%.2f", totalPrice);
String str = "共 " + totalCountStr + "件商品,"
+ "已付款¥" + totalPriceStr + "元";
SpannableStringBuilder style = new SpannableStringBuilder(str);
style.setSpan(new ForegroundColorSpan(Color.RED), 1, (totalCountStr +1), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new ForegroundColorSpan(Color.RED), (totalCountStr+9), (str.length()-1), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mTextView.setText(style);