同一TextView上内容的不同显示(最新)-SpannableString

上次发了一篇同一TextView内容的不同显示这篇文章。

有关颜色的不同显示,我使用了最简单可是也最复杂的方法。忘记使用SpannableString,现又一次发一下,大家參考下。

TextView组件改变部分文字的颜色如今有两种办法,一种是比較笨的方法敲打

TextView textView = (TextView)findViewById(R.id.textview);

textView.setText(Html.fromHtml("<font color="#ff0000">红色</font>其他颜色"));

这样的办法上一篇文章已经写了样例这里不作过多说明。

另外一种用到了SpannableString 这个东东。

先举样例:

首先是color文件

<color name="remind">#25a7f2</color>
<color name="sports_value">#3a3f47</color>
然后正题

String str = "路人甲回复路人乙:你是个棒槌!";
SpannableString spanString = new SpannableString(str);

spanString.setSpan(Object what, int start, int end, int flags);


四个属性,前三个,第一个是方法,第二个是開始位置 第三个是结束位置,

注意:包括開始位置不包括结束位置

int endTwo=str.indexOf("回复");
int endThree=str.indexOf(":");
spanString.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.remind)), 0, endTwo, 

Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
spanString.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.sports_value)), endTwo, 

endTwo+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
spanString.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.remind)), endTwo+2, 

endThree+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
spanString.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.sports_value)), endThree+1, 

str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
textView.setText(spanString);


上面这个new ForegroundColorSpan(mContext.getResources().getColor(R.color.remind)),是设置字体颜色

换成new BackgroundColorSpan(mContext.getResources().getColor(R.color.remind)),就会变成设置背景颜色

还有非常多诸如超链接。斜体等属性设置就不一一举例了。

自己使用过程中研究掌握的会好一点,大笑我的作用是给那些不知道这个东东属性的童鞋一个提醒。

最后:效果图:


ps:尴尬欢迎转载,请加地址http://blog.csdn.net/jing110fei/article/details/41249073


原文地址:https://www.cnblogs.com/jzssuanfa/p/6728827.html