Deep understanding of TextView implementation Rich Text-set different font styles in the same TextView

Source: Internet
Author: User

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.
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:

Copy codeThe Code is as follows: 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, the font is multiplied by proportion, and zoon in is enlarged when the value is greater than 1 ), 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 coloring, that is, color of words. The parameters are consistent with those of background coloring.
• 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 <Document>.
Both SpannableString and SpannableStringBuilder have a method to set the preceding Span:
Copy codeThe Code is as follows :/**
* 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 on both ends
• Spanned. SPAN_EXCLUSIVE_INCLUSIVE --- does not contain the end start, but contains the end point of 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.
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 <Document>
• Linkify. EMAIL_ADDRESS -- only identifies the Email address in TextView as a hyperlink. After clicking it, it will jump to the Email address 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.
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. 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.
InstanceCopy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout
Xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: orientation = "vertical">
<ScrollView
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content">
<LinearLayout
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: orientation = "vertical">
<TextView
Android: id = "@ + id/text_view_font_1"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
/>
<TextView
Android: id = "@ + id/text_view_font_2"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
/>
<TextView
Android: id = "@ + id/text_view_font_3"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
/>
<TextView
Android: id = "@ + id/text_view_font_4"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
/>
<TextView
Android: id = "@ + id/text_view_font_5"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
/>
</LinearLayout>
</ScrollView>
</LinearLayout>

Source code:Copy codeThe Code is as follows: package com. android. Valid tive;
Import java. util. regex. Matcher;
Import java. util. regex. Pattern;
Import android. app. Activity;
Import android. graphics. Color;
Import android. graphics. Typeface;
Import android. OS. Bundle;
Import android. text. Spannable;
Import android. text. SpannableString;
Import android. text. SpannableStringBuilder;
Import android. text. style. AbsoluteSizeSpan;
Import android. text. style. BackgroundColorSpan;
Import android. text. style. ForegroundColorSpan;
Import android. text. style. QuoteSpan;
Import android. text. style. RelativeSizeSpan;
Import android. text. style. ScaleXSpan;
Import android. text. style. StrikethroughSpan;
Import android. text. style. StyleSpan;
Import android. text. style. TypefaceSpan;
Import android. text. style. URLSpan;
Import android. text. util. Linkify;
Import android. widget. TextView;
Public class TextViewFontActivity extends Activity {
@ Override
Public void onCreate (Bundle bundle ){
Super. onCreate (bundle );
SetContentView (R. layout. textview_font_1 );

// Demonstration of basic SpannableString and spans usage
Final TextView textWithString = (TextView) findViewById (R. id. text_view_font_1 );
String w = "The quick fox jumps over the lazy dog ";
Int start = w. indexOf ('q ');
Int end = w. indexOf ('k') + 1;
Spannable word = new SpannableString (w );
Word. setSpan (new AbsoluteSizeSpan (22), start, end,
Spannable. SPAN_INCLUSIVE_INCLUSIVE );
Word. setSpan (new StyleSpan (Typeface. BOLD), start, end,
Spannable. SPAN_INCLUSIVE_INCLUSIVE );
Word. setSpan (new BackgroundColorSpan (Color. RED), start, end,
Spannable. SPAN_INCLUSIVE_INCLUSIVE );
TextWithString. setText (word );

// Demonstration of basic SpannableStringBuilder and spans usage
Final TextView textWithBuilder = (TextView) findViewById (R. id. text_view_font_2 );
SpannableStringBuilder word2 = new SpannableStringBuilder ();
Final String one = "Freedom is nothing but a chance to be better! ";
Final String two = "The quick fox jumps over the lazy dog! ";
Final String three = "The tree of liberty must be refreshed from time to time with" +
"The blood of patroits and tyrants! ";
Word2.append (one );
Start = 0;
End = one. length ();
Word2.setSpan (new StyleSpan (Typeface. BOLD_ITALIC), start, end, Spannable. SPAN_EXCLUSIVE_EXCLUSIVE );
Word2.append (two );
Start = end;
End + = two. length ();
Word2.setSpan (new ForegroundColorSpan (Color. CYAN), start, end,
Spannable. SPAN_EXCLUSIVE_EXCLUSIVE );
Word2.append (three );
Start = end;
End + = three. length ();
Word2.setSpan (new URLSpan (three), start, end, Spannable. SPAN_EXCLUSIVE_EXCLUSIVE );
TextWithBuilder. setText (word2 );

// Troubleshooting when using SpannableStringBuilder
Final TextView textTroubles = (TextView) findViewById (R. id. text_view_font_3 );
SpannableStringBuilder word3 = new SpannableStringBuilder ();
Start = 0;
End = one. length ();
// Caution: must first append or set text to SpannableStringBuilder or SpannableString
// Then set the spans to them, otherwise, IndexOutOfBoundException is thrown when setting spans
Word3.append (one );
// For AbsoluteSizeSpan, the flag must be set to 0, otherwise, it will apply this span to until end of text
Word3.setSpan (new AbsoluteSizeSpan (22), start, end, 0); // Spannable. SPAN_INCLUSIVE_INCLUSIVE );
// For BackgroundColorSpanSpan, the flag must be set to 0, otherwise, it will apply this span to end of text
Word3.setSpan (new BackgroundColorSpan (Color. DKGRAY), start, end, 0); // Spannable. SPAN_INCLUSIVE_INCLUSIVE );
Word3.append (two );
Start = end;
End + = two. length ();
Word3.setSpan (new TypefaceSpan ("sans-serif"), start, end,
Spannable. SPAN_INCLUSIVE_INCLUSIVE );
// TODO: sometimes, flag must be set to 0, otherwise it will apply the span to until end of text
// Which MIGHT has nothing to do with specific span type.
Word3.setSpan (new StyleSpan (Typeface. BOLD_ITALIC), start, end, 0); // Spannable. SPAN_INCLUSIVE_INCLUSIVE );
Word3.setSpan (new ScaleXSpan (0.618f), start, end, Spannable. SPAN_INCLUSIVE_INCLUSIVE );
Word3.setSpan (new StrikethroughSpan (), start, end, 0); // Spannable. SPAN_INCLUSIVE_INCLUSIVE );
Word3.setSpan (new ForegroundColorSpan (Color. CYAN), start, end, Spannable. SPAN_INCLUSIVE_INCLUSIVE );
Word3.setSpan (new QuoteSpan (), start, end, 0); // Spannable. SPAN_INCLUSIVE_INCLUSIVE );
Word3.append (three );
Start = end;
End + = three. length ();
Word3.setSpan (new RelativeSizeSpan (float) Math. E), start, end, Spannable. SPAN_INCLUSIVE_INCLUSIVE );
Word3.setSpan (new ForegroundColorSpan (Color. BLUE), start, end, Spannable. SPAN_INCLUSIVE_INCLUSIVE );
TextTroubles. setText (word3 );

// Highlight some patterns
Final String four = "The gap between the best software engineering" +
"Practice and the average practice is very wide extends perhaps wider" +
"Than in any other engineering discipline. A tool that disseminates" +
"Good practice wocould be important. zookeeper Fred Brooks ";
Final Pattern highlight = Pattern. compile ("");
Final TextView textHighlight = (TextView) findViewById (R. id. text_view_font_4 );
SpannableString word4 = new SpannableString (four );
Matcher m = highlight. matcher (word4.toString ());
While (m. find ()){
Word4.setSpan (new StyleSpan (Typeface. BOLD_ITALIC), m. start (), m. end (),
Spannable. SPAN_INCLUSIVE_INCLUSIVE );
Word4.setSpan (new ForegroundColorSpan (Color. RED), m. start (), m. end (),
Spannable. SPAN_INCLUSIVE_INCLUSIVE );
Word4.setSpan (new StrikethroughSpan (), m. start (), m. end (),
Spannable. SPAN_INCLUSIVE_INCLUSIVE );
}
TextHighlight. setText (word4 );

// Set numbers, URLs and E-mail address to be clickable with TextView # setAutoLinkMask
Final TextView textClickable = (TextView) findViewById (R. id. text_view_font_5 );
Final String contact = "Email: mvp@microsoft.com \ n" +
"Phone: + 47-24885883 \ n" +
"Fax: + 47-24885883 \ n" +
"HTTP: www.microsoft.com/mvp.asp ";
// Set the attribute first, then set the text. Otherwise, it won't work
TextClickable. setAutoLinkMask (Linkify. ALL); // or set 'android: autolink' in layout xml
TextClickable. setText (contact );
}
}

The results:


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.