Here's the first look:
OK, sometimes in our project will ask TextView Chinese text has a part of the font color is different, then we should use
Spannablestringbuilder this tool class, of course, the function of this class is very powerful, here I just implement the above style, the others do not introduce,
the implementation interface of the Spannablestringbuilder is Spannable This interface, and Spannable finally implements the Charsequence, so we're straight
Can be set by Textview.settext ().
The implementation code is given below:
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 all text * @param HIGHLIGHTSTR change the color of the text * @param color 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)) {/* * * Returns the index at the first occurrence of the HIGHLIGHTSTR string in the Wholestr string. */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;}}
Of course the first step above is to get the starting position of the text you want to change color to the end position, and then passSpannablestringbuilder To change the text
The color.
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 = "Want to change the color behind this is the colour to change"; Stringformatutil spanstr = new Stringformatutil (this, Wholestr, "which is the color to change", R.color.blue). FillColor (); tv_show.settext (Spanstr.getresult ());}}
Reprint Please specify source:http://blog.csdn.net/hai_qing_xu_kong/article/details/44225955 Emotional Control _
Learn about Android together how to set the font color for different fields in TextView (22)