[API Guides] format and style of Android string resources, guidesandroid

Source: Internet
Author: User

[API Guides] format and style of Android string resources, guidesandroid

Reprinted please indicate the source: http://blog.csdn.net/zhaokaiqiang1992

This article translated from Android Development Guide and introduced how to format string resources and set different styles.
To view the original text, stamp it here

  • Format and style of string Resources
    • Be careful with the marker and quote.
    • Format a string
    • Add a style in HTML

Be careful when formatting and styles string Resources

If our string resource contains an asterisk ('), we must add a transfer character to it (\'), or enclose a pair of quotation marks outside the string. Here is an example:

<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> <! -- May cause compilation errors -->

If your string contains double quotation marks, you must use (\ ") instead. Wrapping single quotes outside the string does not work.

<String name = "good_example"> This is a \ "good string \". </string> <string name = "bad_example"> This is a "bad string ". </string> <! -- The quotation marks are ignored. The final result is: This is a bad string. --> <string name = "bad_example_2"> 'this is another "bad string ". '</string> <! -- May cause compilation errors -->
Format a string

If you need to use String. format (String, Object ...) To format the string in this way, you can put your formatting parameters in the string resource file. Here is an example of this resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

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

Resources res = getResources();String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
Add a style in HTML

You can use HTML tags to add styles for your strings. The following is an example:

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

Supported HTML element tags include:

  • Bold Chinese
  • Italics
  • Underline

Sometimes, you may want to create a String resource with a formatting parameter and a formatting style. Generally, this does not work because String. format (String, Object…) is used directly ...) All style information is filtered out. After formatting, you need to use Html. fromHtml () to display the ELE. Me effect of the HTML Tag:

  • Store style text as HTML Escape strings
<resources>  <string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string></resources>

In this formatted string,The tag is added. Note that the Left brackets are replaced by HTML Escape strings.

  • In this way, the formatted string is the same as the normal one, but we also need to call Html. fromHtml () to convert the HTML tag to the style text.
Resources res = getResources();String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);CharSequence styledText = Html.fromHtml(text);
  • Complete Encode (username. For example, if you want to give String. format () to pass a character similar to "<" or "&", we must remove these special symbols before formatting, in this way, the formatted characters are passed to Html. after fromHtml (text), the characters will be displayed as they are written at the beginning. For example:
String escapedUsername = TextUtil.htmlEncode(username);Resources res = getResources();String text = String.format(res.getString(R.string.welcome_messages), escapedUsername, mailCount);CharSequence styledText = Html.fromHtml(text);
  • Set styles with Spannables
    With 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 in the android. text. style package to apply the style.

We can use the following help method to create most of the spannable text.

/** * Returns a CharSequence that concatenates the specified array of CharSequence * objects and then applies a list of zero or more tags to the entire range. * * @param content an array of character sequences to apply a style to * @param tags the styled span objects to apply to the content *        such as android.text.style.StyleSpan * */private static CharSequence apply(CharSequence[] content, Object... tags) {    SpannableStringBuilder text = new SpannableStringBuilder();    openTags(text, tags);    for (CharSequence item : content) {        text.append(item);    }    closeTags(text, tags);    return text;}/** * Iterates over an array of tags and applies them to the beginning of the specified * Spannable object so that future text appended to the text will have the styling * applied to it. Do not call this method directly. */private static void openTags(Spannable text, Object[] tags) {    for (Object tag : tags) {        text.setSpan(tag, 0, 0, Spannable.SPAN_MARK_MARK);    }}/** * "Closes" the specified tags on a Spannable by updating the spans to be * endpoint-exclusive so that future text appended to the end will not take * on the same styling. Do not call this method directly. */private static void closeTags(Spannable text, 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 demonstrates how to use these methods to achieve our effects, such as bold, italic, and color. You can also use this method to complete other text styles.

/** * Returns a CharSequence that applies boldface to the concatenation * of the specified CharSequence objects. */public static CharSequence bold(CharSequence... content) {    return apply(content, new StyleSpan(Typeface.BOLD));}/** * Returns a CharSequence that applies italics to the concatenation * of the specified CharSequence objects. */public static CharSequence italic(CharSequence... content) {    return apply(content, new StyleSpan(Typeface.ITALIC));}/** * Returns a CharSequence that applies a foreground color to the * concatenation of the specified CharSequence objects. */public static CharSequence color(int color, CharSequence... content) {    return apply(content, new ForegroundColorSpan(color));}

The following code demonstrates how to use method chains to generate different text styles for individual words:

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

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.