Android sets multiple font colors for TextView

Source: Internet
Author: User
Tags getcolor gettext

The effect is as follows:

/**
*@paramTextView
*@paramPositionsThe position of discoloration
*@paramColorsMultiple color values, number and number of positions can be inconsistent, if the color value is less than the position value, it is used to cross the
*@ descriptionSet a textivew to display multiple colors
*@ AuthorTll
*@ Time2016/11/11 10:37
*/
public static voidSetmultiplecolor (TextView TextView, list<integer> positions, Integer ... colors) {
if (IsEmpty (positions)) {
Return
}
Spannablestringbuilder Builder =New Spannablestringbuilder (Textview.gettext (). toString ());
for (int i =0; I < Positions.size (); i++) {
Foregroundcolorspan span =New Foregroundcolorspan (colors[i% colors.Length]);
if (i = =0) {
Builder.setspan (span, 0, Positions.get (i), spannable. span_exclusive_exclusive);
} Else {
Builder.setspan (span, positions.get (i- 1), Positions.get (i), spannable. span_exclusive_exclusive);
}
}
Textview.settext (builder);
}

How to use:
Text = (TextView) Findviewbyid (r.id.Text;
list<integer> positions =New Arraylist<> ();
Positions.add (4);
Positions.add (6);
Positions.add (11);
Positions.add (13);
Positions.add (Text.gettext (). toString (). Length ());
Setmultiplecolor (Text, positions,< Span style= "COLOR: #6897bb" > < Span style= "COLOR: #cc7832" > getresources (). getcolor (R.color. color_353535) getresources (). GetColor (R.color.color_f67067)"
< Span style= "COLOR: #cc7832" > < Span style= "COLOR: #6897bb" >< Span style= "COLOR: #cc7832" > &NBSP;         

Android sets multiple font colors for TextView

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.