Android TextView Set Colorful text

Source: Internet
Author: User
Tags getcolor gettext

In the application development often encountered the need to insert several different color text in a paragraph of the needs;

I used to use a number of TextView together, not only feel very stupid, operation is also quite disgusting;

Until the contact with the Spannablestringbuilder, feel the whole person is good;

When I set up the interface layout, there will be some default text with a string placeholder, such as: "The current temperature is:%s", "Today's weather:%1 $ s, High:%2$s, lowest temperature:%3$s, rainfall rate:%4$s,pm2.5:%5$s.";

Then, when the data is obtained, the direct String.Format (string target, string ... data) can insert the data in the corresponding position;

Recently encountered an inserted data to be replaced by another color requirements, think that the need should be more common, so wrote a tool class;

1 /**2 * TextView Color tool class3 * Created by me on 2015-08-10.4  */5  Public classTextviewcolorutil {6 7     /**8 * When the text content is "xxxxx%sxxxx" (a format placeholder) or "xxxx%1$sxxxx%2$x......xxxx%n$sxxxx" (multiple formatting placeholders), complete the formatting and set the newly added text color, At the same time can also set the original text color;9 * <p/>Ten * Note: Be sure to use the%s placeholder when using a single format, and use the%n$s placeholder when using multiple formats ; One * The number of placeholders must be the same as the number of strings you want to fill in; A      * -      * @paramtexts if the variable parameter length is 0, do not process; If the text length is 0, the default is "" -      * @paramDefaultcolorid r.color.xxx If you do not want to change the default color (the text color before the colon), you can fill in null the      * @paramNewcontentcolorid r.color.xxx -      */ -      Public Static voidSetsubcolortext (context context, TextView TV, Integer Defaultcolorid,intNewcontentcolorid, String ... texts) { -  +         if(Texts! =NULL) { -             if(Texts.length = = 1) {//single-format parameter conditions +                 if(Defaultcolorid! =NULL)//1. If you have set the default text color, give the change A Tv.settextcolor (Defaultcolorid); at  -String Text = texts[0]; -                 if(Stringutil.isempty (text))//2. If the text content is null or length 0, the default is "" -Text = ""; -  -String Origintext = Tv.gettext (). toString ();//3. Format, record the starting and ending index of the added string in                 intIndexstart = Origintext.indexof ("%s"); -                 intIndexend = Indexstart +text.length (); toString foo =String.Format (origintext, text); + Tv.settext (foo); -  the                 if(Indexend > Indexstart) {//4. If it is necessary to change color, perform *Spannablestringbuilder style =NewSpannablestringbuilder (foo); $Style.setspan (NewForegroundcolorspan (Context.getresources (). GetColor (Newcontentcolorid)), Indexstart, Indexend, Spannable.span _inclusive_exclusive);Panax Notoginseng Tv.settext (style); -                 } the  +}Else if(Texts.length > 1) {//Multi-format A                 if(Defaultcolorid! =NULL)//1. If you have set the default text color, give the change the Tv.settextcolor (Defaultcolorid); +  -                 int[] Indexesstart =New int[texts.length]; $                 int[] Indexesend =New int[texts.length]; $String Origintext =Tv.gettext (). toString (); -  -                  for(inti = 0; i < texts.length; i++) { theString Text =Texts[i]; -                     if(Stringutil.isempty (text)) {//2. If the text content is null or length 0, the default is ""WuyiText = ""; the                     } -  WuString regular = "%" + (i + 1) + "$s";//3. Format, record the starting and ending index of the added string -Indexesstart[i] =Origintext.indexof (regular); About                     if(I > 0) { $                         intIndexfix = 0; -                          for(intj = 0; J <= I-1; J + +) { -String formerregular = "%" + (j + 1) + "$s"; -Indexfix + = (Indexesend[j]-indexesstart[j])-formerregular.length (); A                         } +Indexesstart[i] + =Indexfix; the                     } -Indexesend[i] = Indexesstart[i] +text.length (); $                 } theString foo =String.Format (Origintext, (object[]) texts); the Tv.settext (foo); theSpannablestringbuilder style =NewSpannablestringbuilder (foo); the                  for(inti = 0; i < texts.length; i++) { -                     if(Indexesend[i] > Indexesstart[i])//4. If it is necessary to change color, perform inStyle.setspan (NewForegroundcolorspan (Context.getresources (). GetColor (Newcontentcolorid)), Indexesstart[i], Indexesend[i], spannable.span_inclusive_exclusive); the                 } the Tv.settext (style); About             } the         } the     } the}
Code

There is currently only one color, if there is a need for a different color for each inserted data ... It's a good change.

Change the incoming parameter int newcontentcolorid to int[] newcontentcolorids and then change the logic slightly to OK.

>_>

Let's take an example from the previous two examples:

1.

1 textview.settext ("The current temperature is:%s"); 2 textviewcolorutil.setsubcolortext (mainactivity.  thisnull, R.color.blue, "3°c");
"The current temperature is:%s"

2.

1 tv.settext ("Today's weather:%1 $ s, High:%2$s, lowest temperature:%3$s, rainfall rate:%4$s,pm2.5:%5$s." ); 2 textviewcolorutil.setsubcolortext (mainactivity.  thisnull, r.color.red, "clear", "22°c", "9°c", "47%", "19");
"Today's weather:%1 $ s, High:%2$s, lowest temperature:%3$s, rainfall rate:%4$s,pm2.5:%5$s."

Android TextView Set Colorful text

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.