Implemented by Spannablestringbuilder, it is like the <span> element inside the HTML that changes the text color or background color of the specified text
public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); String str= "This is a demo! that sets the TextView part text background color and foreground color"; int Bstart=str.indexof ("background"), int bend=bstart+ "background". Length (), int fstart=str.indexof ("foreground"), int fend=fstart+ "foreground". Length (); Spannablestringbuilder style=new Spannablestringbuilder (str); Style.setspan (New Backgroundcolorspan (color.red), bstart,bend,spannable.span_exclusive_exclusive); Style.setspan (New Foregroundcolorspan (color.red), fstart,fend,spannable.span_exclusive_inclusive); TextView tvcolor= (TextView) Findviewbyid (R.id.tv_color); Tvcolor.settext (style);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}
- Absolutesizespan (int size)----Set the font size, the parameter is an absolute value, which is equivalent to the font size in Word
- Relativesizespan (float proportion)----Set the font size, the parameter is a multiple of the default font size, such as the default font size is x, then the font size after the set is X*proportion, which is more flexible to use. Proportion>1 is zoom in (zoom in), proportion<1 is zoom out (zoom Out)
- Scalexspan (float proportion)----scaled font, similar to the above, the default is 1, set is the original multiplied by proportion, greater than 1 o'clock magnification (zoon in), smaller than when zoomed out (zoom out)
- Backgroundcolorspan (int color)----background coloring, parameters are color values, you can use the constants defined in Android.graphics.Color directly, or with COLOR.RGB (int, int, int)
- Foregroundcolorspan (int color)----foreground coloring, which is the coloring of words, with parameters consistent with background coloring
- Typefacespan (String family)----font, parameter is the name of the font such as "sans", "Sans-serif" and so on
- Stylespan (Typeface style)-----font style, such as bold, italic, parameters are constants defined in Android.graphics.Typeface, such as typeface.bold,typeface.italic and so on.
- Strikethroughspan----If this style is set, there will be a line that crosses all the words in the middle, as if it were crossed out.
Android TextView set part text background color and text color