1. 第一种使用SpannableStringBuilder
//部分文字改变颜色 //ForegroundColorSpan 为文字前景色,BackgroundColorSpan为文字背景色 ForegroundColorSpan redSpan = new ForegroundColorSpan(getResources().getColor(R.color.text_red)); ForegroundColorSpan graySpan = new ForegroundColorSpan(getResources().getColor(R.color.text_gray)); mTextView.setText("灰色红色"); //这里注意一定要先给textview赋值 SpannableStringBuilder builder = new SpannableStringBuilder(mTextView.getText().toString()); //为不同位置字符串设置不同颜色 builder.setSpan(graySpan, 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); builder.setSpan(redSpan, 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //最后为textview赋值 mTextView.setText(builder);
2. 第二种,使用Html.fromHtml()
TextView desc1 = (TextView)findViewById(R.id.desc1);TextView desc2 = (TextView)findViewById(R.id.desc2);TextView desc3 = (TextView)findViewById(R.id.desc3);String content1 = "务必使用<font color='red'>银行卡</font>开户时<font color='red'>预留手机号</font>!";String content2 = "点击获取验证码按钮后,您将收到<font color='red'>银行验证码短信</font>!";String content3 = "时间<font color='red'>工作日09:00 - 次日06:00</font>!";desc1.setText(Html.fromHtml(content1));desc2.setText(Html.fromHtml(content2));desc3.setText(Html.fromHtml(content3));
3. 总结
1.使用SpannableStringBuilder由于颜色是在本地定义的,所以可以精确地控制要显示的颜色,兼容性最好。
缺点也很明显太麻烦了,需要为每一种颜色定义一个ForegroundColorSpan
2. 使用Html方式则相对比较简单,直接在字符串里面使用标签即可,但是缺点也相对明显,只能使用标签里面预定义的集中颜色值,与本地兼容性不是很好。
4. 若还有其他方式欢迎指出。