Android ---- SpannableString, spannablestring

Source: Internet
Author: User

Android ---- SpannableString, spannablestring
1. Background

In the process of application development, it is often seen that some information with different font styles is like the time and charging information on the default LockScreen. In a similar situation, the first possible response is to use different textviews. Different font styles are set for each TextView to meet the requirements.

Android is recommended. text. *; and android. text. style. *; the following component implements RichText: that is, set different font styles in the same TextView. For some applications, such as text editing, notepad, MMS, and SMS, you must use these components to achieve the desired display effect.

The main basic tool classes are android. text. Spanned; android. text. SpannableString; android. text. SpannableStringBuilder; these classes are used to replace regular strings. SpannableString and SpannableStringBuilder can be used to set different spans. These spans are used to implement Rich Text, such as bold, italic, foreground color, background color, font size, and font style. android. text. style. * defines many Span types for use.

This is the related API Class General Hierarchy:

 

Because Spannable and so on finally implement the CharSequence interface, you can directly set SpannableString and SpannableStringBuilder to TextView through TextView. setText.

 

2. Usage

When you want to display Rich Text information, you can create a SpannableString or SpannableStringBuilder. The difference is that SpannableString is like a String, and a String is input when constructing an object, after that, you cannot change the String content or splice multiple spannablestrings. The SpannableStringBuilder is more like a StringBuilder. It can splice multiple strings through its append () method:

SpannableString word = new SpannableString("The quick fox jumps over the lazy dog");SpannableStringBuilder multiWord = new SpannableStringBuilder();multiWord.append("The Quick Fox");multiWord.append("jumps over");multiWord.append("the lazy dog");

After the Spannable object is created, you can set the Span for them to implement the expected Rich Text. Common spans include:

  • 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. For example, if the default font size is x, the configured font size is x * proportion, this is more flexible to use. proportion> 1 is zoom in, and proportion <1 is zoom out)
  • ScaleXSpan (float proportion) ---- scale the font. Similar to the preceding one, the default value is 1. After setting it, It is multiplied by proportion. If it is greater than 1, it is zoon in ), zoom out)
  • BackgroundColorSpan (int color) ---- background coloring. The parameter is a Color value. You can directly use the constant defined in android. graphics. Color, or use color. rgb (int, int, int)
  • ForegroundColorSpan (int color) ---- foreground color, that is, the color of the word. The parameter is consistent with that of the background color.
  • TypefaceSpan (String family) ---- font. The parameter is the font name, such as "sans" and "sans-serif ".
  • StyleSpan (Typeface style) ----- font style, such as BOLD and ITALIC. The parameters are constants defined in android. graphics. Typeface, such as Typeface. BOLD and Typeface. ITALIC.
  • StrikethroughSpan ---- if this style is set, there will be a line passing through all words from the middle, just like being crossed out.

When using these Sytle spans, you can only pass the preceding constructor parameters. You do not need to set other attributes. If you need them, you can also set other attributes for them, for more information, see the documentation.
Both SpannableString and SpannableStringBuilder have a method to set the preceding Span:

/** * Set the style span to Spannable, such as SpannableString or SpannableStringBuilder * @param what --- the style span, such as StyleSpan * @param start --- the starting index of characters to which the style span to apply * @param end --- the ending index of characters to which the style span to apply * @param flags --- the flag specified to control */setSpan(Object what, int start, int end, int flags);

Among them, what is the Style span to be set, start and end are the start position of Span in String, and flags are used to control behavior, it is usually set to 0 or a constant defined in Spanned. Commonly Used constants include:

  • Spanned. SPAN_EXCLUSIVE_EXCLUSIVE --- does not contain the endpoints of start and end at both ends
  • Spanned. SPAN_EXCLUSIVE_INCLUSIVE --- does not contain end start, but contains the end
  • Spanned. SPAN_INCLUSIVE_EXCLUSIVE --- contains the start at both ends, but does not include the endpoint of the end.
  • Spanned. SPAN_INCLUSIVE_INCLUSIVE --- contains the endpoints of start and end at both ends

It is like defining a range in mathematics, and opening or closing a range is the same. There are many other flags. For more information, see here. Here, we will focus on parameter 0. In many cases, if the preceding parameter is set, Span will be applied from start to end of Text, rather than between start and end, in this case, Flag 0 is required.

3. Linkify

In addition, you can also use TextView. setAutoLink (int) sets its Linkify attribute. In this case, TextView automatically checks its content and identifies the phone number, web address or email address as a hyperlink. You can click, click to jump to the corresponding application, such as Dialer, Browser, or Email. Linkify has several common options. For more information, see:

  • Linkify. EMAIL_ADDRESS -- only identifies the Email address in the TextView as a hyperlink. After clicking it, it will jump to the Email and send an Email to this address.
  • Linkify. PHONE_NUMBERS -- only identifies the phone number in TextView as a hyperlink. After clicking it, it will jump to Dialer and Call this number.
  • Linkify. WEB_URLS -- only identifies the URL in TextView as a hyperlink. After clicking it, the URL is displayed in Browser.
  • Linkify. ALL -- this option identifies the special Uris supported by ALL systems, and then performs the corresponding operations.
4. Weight Selection

I personally think that the most common problem in software development is not how to use a certain technique, but when to use it, because there may be N different ways to achieve the same goal, we need to weigh the pros and cons and select the most appropriate one. As the saying goes, there is no best, but the most suitable cloud. As discussed earlier, you can use multiple textviews in addition to Style Span to display different information in different fonts. We need to summarize when to use StyleSpan and when to use multiple textviews:

    1. If multiple different categories of information are displayed, multiple textviews should be used to conveniently control and change their respective information. The example is the date and charging information on LockScreen by default, because they carry different information, multiple textviews should be used to present them separately.
    2. If the display is the same class information or the same information, StyleSpan should be used. For example, in a short message, you need to Highlight the relevant information of the contact, or want some information such as Highlight.
    3. If you want to implement Rich text, you can only use Style span.
    4. If you want to implement some special effects, you can also consider using StyleSpan. Setting different font styles is only an elementary application of Style span. If you study it in depth, you can find many amazing effects.

Spannable and ImageSapn can be used in combination to achieve text-and-image mixing in EditText.

 

Below are some instance code

  1. /**
  2. * Hyperlink
  3. */
  4. Private void addUrlSpan (){
  5. SpannableString spanString = new SpannableString ("HYPERLINK ");
  6. URLSpan span = new URLSpan ("tel: 0123456789 ");
  7. SpanString. setSpan (span, 0, 3, Spannable. SPAN_EXCLUSIVE_EXCLUSIVE );
  8. TV. append (spanString );
  9. }
  10. /**
  11. * Text background color
  12. */
  13. Private void addBackColorSpan (){
  14. SpannableString spanString = new SpannableString ("color 2 ");
  15. BackgroundColorSpan span = new BackgroundColorSpan (Color. YELLOW );
  16. SpanString. setSpan (span, 0, 3, Spannable. SPAN_EXCLUSIVE_EXCLUSIVE );
  17. TV. append (spanString );
  18. }
  19. /**
  20. * Text color
  21. */
  22. Private void addForeColorSpan (){
  23. SpannableString spanString = new SpannableString ("color 1 ");
  24. ForegroundColorSpan span = new ForegroundColorSpan (Color. BLUE );
  25. SpanString. setSpan (span, 0, 3, Spannable. SPAN_EXCLUSIVE_EXCLUSIVE );
  26. TV. append (spanString );
  27. }
  28. /**
  29. * Font size
  30. */
  31. Private void addFontSpan (){
  32. SpannableString spanString = new SpannableString ("font 36 ");
  33. AbsoluteSizeSpan span = new AbsoluteSizeSpan (36 );
  34. SpanString. setSpan (span, 0, 5, Spannable. SPAN_EXCLUSIVE_EXCLUSIVE );
  35. TV. append (spanString );
  36. }
  37. /**
  38. * Bold and italic
  39. */
  40. Private void addStyleSpan (){
  41. SpannableString spanString = new SpannableString ("BIBI ");
  42. StyleSpan span = new StyleSpan (Typeface. BOLD_ITALIC );
  43. SpanString. setSpan (span, 0, 2, Spannable. SPAN_EXCLUSIVE_EXCLUSIVE );
  44. TV. append (spanString );
  45. }
  46. /**
  47. * Strikethrough
  48. */
  49. Private void addStrikeSpan (){
  50. SpannableString spanString = new SpannableString ("strikethrough ");
  51. StrikethroughSpan span = new StrikethroughSpan ();
  52. SpanString. setSpan (span, 0, 3, Spannable. SPAN_EXCLUSIVE_EXCLUSIVE );
  53. TV. append (spanString );
  54. }
  55. /**
  56. * Underline
  57. */
  58. Private void addUnderLineSpan (){
  59. SpannableString spanString = new SpannableString ("underline ");
  60. UnderlineSpan span = new UnderlineSpan ();
  61. SpanString. setSpan (span, 0, 3, Spannable. SPAN_EXCLUSIVE_EXCLUSIVE );
  62. TV. append (spanString );
  63. }
  64. /**
  65. * Image
  66. */
  67. Private void addImageSpan (){
  68. SpannableString spanString = new SpannableString ("");
  69. Drawable d = getResources (). getDrawable (R. drawable. ic_launcher );
  70. D. setBounds (0, 0, d. getIntrinsicWidth (), d. getIntrinsicHeight ());
  71. ImageSpan span = new ImageSpan (d, ImageSpan. ALIGN_BASELINE );
  72. SpanString. setSpan (span, 0, 1, Spannable. SPAN_EXCLUSIVE_EXCLUSIVE );
  73. TV. append (spanString );
  74. }
  75. }

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.