Reference: http://blog.csdn.net/fengyoujie/article/details/42783891
In practical applications, it is necessary to display a string with different colors and fonts. Of course, it can be spliced out through different textviews. It can also be displayed through a textview.
Proceed as follows:
1. Define different styles.
Might as well define 2 styles as follows
<style name="style0"> <item name="android:textSize">19dip</item> <item name="android:textColor">@color/color1</item> </style> <style name="style1"> <item name="android:textSize">23dip</item> <item name="android:textColor">@color/color2</item> <item name="android:textStyle">italic</item> </style>
. Set the string format via SpannableString. code show as below:
mTextView = (TextView)findViewById(R.id.test); SpannableString styledText = new SpannableString("Dear little treasure, hello"); styledText.setSpan(new TextAppearanceSpan(this, R.style.style0), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); styledText.setSpan(new TextAppearanceSpan(this, R.style.style1), 3, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); mTextView.setText(styledText, TextView.BufferType.SPANNABLE);