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

Source: Internet
Author: User
Tags int size
Background information
In the development application process, you often encounter information that displays a number of different font styles like the default lockscreen time and charge information. For a similar scenario, the first reaction might be to use a different number of TextView for each textview to set a different font style to meet the requirements.

The recommended approach here is to use the android.text.* and android.text.style.* components to implement RichText: You can also set different font styles in the same textview. For some applications, such as text editing, Notepad, MMS, SMS and other places, you must also use these components to achieve the desired display.

The main basic tool class has android.text.Spanned; android.text.SpannableString; Android.text.SpannableStringBuilder; Use these classes instead of a regular string. Spannablestring and Spannablestringbuilder can be used to set different spans, which are used to implement rich Text, such as bold, italic, foreground, background color, font size, font style, and so on, A number of span types are defined in the android.text.style.* to use.

This is the class general hierarchy of the associated API:

Because Spannable and so on finally realized the Charsequence interface, so can directly spannablestring and Spannablestringbuilder through Textview.settext () set to TextView.
How to use
When you want to display rich text information, you can use to create a spannablestring or Spannablestringbuilder, and the difference is that spannablestring is like a string, When you construct an object, you pass in a string, you cannot change the contents of the string, and you cannot stitch multiple spannablestring; Spannablestringbuilder is more like StringBuilder, It can stitch multiple strings by its append () method:

Copy Code code 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");

Once you have created the Spannable object, you can set a span for them to achieve the rich text you want, and the common spans are:
absolutesizespan (int size)----Sets the font size, which is an absolute value, equivalent to the font size in Word
Relativesizespan (float proportion)----Set the font size, the parameter is relative to the default font size, such as the default font size is x, then the font size is set after the X*proportion, which is more flexible, Proportion>1 is magnification (zoom in), proportion<1 is narrowing (zoom out)
Scalexspan (float proportion)----zoom font, similar to the above, the default is 1, set is the original times proportion, greater than 1 o'clock magnification (zoon in), smaller than (zoom out)
backgroundcolorspan (int color)----background coloring, parameters are color values, you can directly use the constants defined in Android.graphics.Color, or with COLOR.RGB (int, int, int)
foregroundcolorspan (int color)----foreground coloring, that is, the color of the word, the parameters are consistent with the background coloring
Typefacespan (String family)----font, parameter is the name of the font such as "sans", "Sans-serif" and so on
Stylespan (typeface style)-----font style, such as bold, italic, Parameters are constants defined inside the android.graphics.Typeface, such as Typeface.bold,typeface.italic, and so on.
Strikethroughspan----If this style is set, a line will pass through all the words in the middle, as if it were crossed out.
For these sytle spans, when used, they usually only pass the construction parameters described above, you do not need to set other properties, and if necessary, you can set other properties, please see < Document>.
both spannablestring and Spannablestringbuilder have a way to set these spans:
Copy Code code 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);

Where the parameter what is the style span,start and end to be set is the starting position of the span in the identity string, and flags are used to control the behavior, usually set to the constants defined in 0 or spanned, commonly used:
spanned.span_exclusive_exclusive---does not contain endpoints with both ends of start and end
The spanned.span_exclusive_inclusive---does not contain end start, but contains the endpoint at which it is located
The spanned.span_inclusive_exclusive---contains both ends of start, but does not contain the endpoint where the end is located
spanned.span_inclusive_inclusive---Contains endpoints with both ends of start and end
This is understood to be like a mathematical definition of intervals, open intervals or closed intervals. There are many other flag that can refer to < here>. Here's a note about parameter 0, there are many times, if the above parameters are set, then span will apply from start to the text end, rather than between the start and ends, this time you need to use flag 0.
linkify
Alternatively, you can set its Linkify property by Textview.setautolink (int), which is useful in that TextView automatically checks its contents and identifies phone number, web address, or e-mail address , and identified as hyperlinks, clickable, click and then jump to the corresponding application, such as dialer,browser or email. Linkify has several common options, please refer to < Document>
linkify.email_address---only identify the email address in the TextView, identified as a hyperlink, click to jump to email, send email to this location
Linkify.phone_numbers--only identifies the phone number in TextView, identifies it as a hyperlink, and jumps to dialer,call this number when clicked.
linkify.web_urls--only identifies the URL in TextView, identifies it as a hyperlink, and jumps to browser when clicked to open this URL
Linkify.all--this option is to identify the special URI supported by all systems, and then do the appropriate action
Tradeoff Selection
Personally, the most common problem with software development is not the question of how a technique is used, it's a question of when and how to use it, because there may be n different ways to achieve the same goal, to weigh the pros and cons, to choose the most appropriate one, as the saying goes, there is no best, only the most suitable. As discussed earlier, in order to use different fonts to display different information possible solutions, in addition to using style span can also use multiple TextView. Then you need to summarize when to use Stylespan and when to use multiple TextView:
1. If you are displaying multiple different categories of information, you should use multiple TextView, which also facilitates control and change of your information, as in the case of the default Lockscreen date and charge information, because they carry different information, So you should use multiple TextView to render them separately.
2. If you are displaying the same type of information, or the same information, you should use Stylespan. For example, in short messages, the contact information should be highlighted, or you want to highlight some information.
3. If you want to implement rich text, there is no way to use style span only.
4. If you want to achieve some special effects, you can also consider using Stylespan. Setting a different font style is just the primary application of style span, and if you look at it in depth, you can find a lot of wonderful effects.
Instance
Copy Code code 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 Code code as follows:

Package com.android.effective;
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, 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 no but a chance to being better!";
Final String two = "The quick fox jumps over the lazy dog!";
Final String three = "The Tree of Liberty must is refreshed from"
"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 the append or set text to Spannablestringbuilder or spannablestring
Then set the spans to them, otherwise, indexoutofboundexception are thrown when setting spans
Word3.append (one);
For Absolutesizespan, the flag must is set to 0, otherwise, it'll apply this span to until end of text
Word3.setspan (New Absolutesizespan, start, end, 0);//spannable.span_inclusive_inclusive);
For Backgroundcolorspanspan, the flag must is set to 0, otherwise, it'll apply this span 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 is set to 0, otherwise it would 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¡ªperhaps wider" +
"than in the any other engineering discipline." A tool that disseminates "+
"Good practice would be important.¡ªfred Brooks";
Final pattern highlight = Pattern.compile ("the");
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 is 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, 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.