Formatting and styling of the "API Guides" Android string resource

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/zhaokaiqiang1992

This article, translated from the Android Development Guide, describes how to format and set different styles for string resources.
Want to see the original, please poke here

    • Formatting and styling of string resources
      • Be careful of the apostrophe and the reference number of the pits
      • formatting strings
      • Add styles with HTML

Formatting and styling of string resources beware of apostrophes and reference number pits

If our string resource has an apostrophe ('), then we have to add the transfer character to it (\ '), or wrap a pair of quotes around the outer string. Let's look at an example below:

<string name="good_example">This\‘ll work</string><string name="good_example_2">"This‘ll also work"</string><string name="bad_example">This doesn‘t work</string>    <!-- 会造成编译错误 -->

If your string has double quotes, then you have to use (\ ") instead. Wrapping a single quotation mark outside a string is not useful.

<string  name  = "good_example" ;  this is a \ " Good string\ ". </string ;  <string  name  =< Span class= "Hljs-value" > "bad_example" ; this is a ' bad string '. </string ;  <!--quotation marks are ignored, and the final result is: The is a bad string.-->  <string  name  =< Span class= "Hljs-value" > "bad_example_2" ; ' This is another ' bad string '. ' </string ;  <!--will cause compilation errors-->  
formatting strings

If you need to format the string with String.Format (String, Object ...), then you can put your formatting parameters in the string's resource file, let's take an example of this resource:

<string name="welcome_messages">%1$s!%2$dnew messages.</string>

In the above example, there are two formatting parameters,%1 sis aaaWordcharacterstringReferencenumber, D is a decimal parameter. You can format the string as follows:

Resources res = getResources();StringtextString.format(res.getString(R.string.welcome_messages), username, mailCount);
Add styles with HTML

You can use HTML tags to add styles to your string, and here's an example:

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="welcome"><b>Android</b>!</string></resources>

Supported HTML element tags include:

    • Bold characters
    • Italic Word
    • Underline

Sometimes you might want to create a string resource that has formatting parameters and can format the style, which generally doesn't work because using String.Format (String, Object ...) directly filters out all of the style information. So after formatting, you need to use html.fromhtml () to display the HTML tag's hunger effect:

    • Store style text as HTML escape string
<Resources>  <stringName="Welcome_messages">Hello,%1$s!You have&LT; b>%2$d NewMessages&LT;/b>.</string></resources>

Inside this formatted string, the tag is added. Note that the left parenthesis is replaced by the HTML escape string <.

    • This format string is the same as normal, but we also need to call html.fromhtml () to convert HTML tags into style text
Resources res = getResources();StringtextString.format(res.getString(R.string.welcome_messages), username, mailCount);CharSequence styledText = Html.fromHtml(text);
    • Because html.fromhtml () will format all the HTML entities, be sure to format the strings to avoid any possible HTML characters, which can be done using Textutil.htmlencode (username). For example, if you want to pass a character like "<" or "&" to String.Format (), then before formatting, we have to remove these special symbols so that when we pass the formatted characters to html.fromhtml ( Text), the character will appear as it was written in the beginning. Let's give an example:
String escapedUsername = TextUtil.htmlEncode(username);Resources res = getResources();StringtextString.format(res.getString(R.string.welcome_messages), escapedUsername, mailCount);CharSequence styledText = Html.fromHtml(text);
    • Setting styles with Spannables
      Using the Spannables object, we can set the font color and font size. You can use Spannablestringbuilder to create your own text, and then use the class inside the Android.text.style package to apply the style.

We can use the following Help method to complete most of the work of creating spannable text

/** * Returns a charsequence thatConcatenates theSpecified array ofCharsequence * Objects and  ThenApplies AList  ofZeroorMore tags to  theEntire range. * * @param content an array of characterSequences toApply a Style to* @param tags theStyled span objects toApply to  theContent * Such asAndroid.text. style. Stylespan * */private static charsequence apply (charsequence[] content, Object ... tags) {spannablestringbuildertext= new Spannablestringbuilder (); Opentags (text, tags); for(charsequenceItem: content) {text. Append (Item); } closetags (text, tags);return text;} /** * Iterates OverAn array ofTags andApplies them to  the beginning  of  theSpecified * Spannable object so thatFuturetextAppended to  the textwould have theStyling * Applied to it. Do notCall the This method directly. */private static void Opentags (spannabletext, object[] tags) { for(Object tag:tags) {text. Setspan (Tag,0,0, Spannable.span_mark_mark); }}/** *"Closes"  theSpecified tags onA spannable byUpdating theSpans toBe * endpoint-exclusive thatFuturetextAppended to  the EndWould notTake * on  theSame styling. Do notCall the This method directly. */private static void Closetags (spannabletext, object[] tags) {int len =text.length(); for(Object tag:tags) {if(Len >0) {text. Setspan (Tag,0, Len, spanned.span_exclusive_exclusive); }Else{text. Removespan (tag); }    }}

The following code shows how we should use these methods to accomplish our effects, such as bold, italic, and color. You can also refer to this practice to complete other text styles

/** * Returns A charsequence that applies boldface to the concatenation * of the specified charsequence objects. */ Public StaticCharsequenceBold(Charsequence ... content) {returnApply (content,NewStylespan (Typeface.bold));}/** * Returns A charsequence that applies italics to the concatenation * of the specified charsequence objects. */ Public StaticCharsequenceItalic(Charsequence ... content) {returnApply (content,NewStylespan (Typeface.italic));}/** * Returns A charsequence that applies a foreground color to the * concatenation of the specified charsequence Obje Cts. */ Public StaticCharsequenceColor(intColor, charsequence ... content) {returnApply (content,NewForegroundcolorspan (color));}

The following code demonstrates how to use a method chain to produce a different text style for individual words:

"hello, ""world"and bold the entire sequence.CharSequence text = bold(italic(res.getString(R.string.hello)),    color(Color.RED, res.getString(R.string.world)));

Formatting and styling of the "API Guides" Android string resource

Related Article

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.