TextView Spnnable used in Android

Source: Internet
Author: User

The design of the project, I immediately thought of using spannablestring to make this effect. But I just have a basic understanding of spannablestring, and I'll keep a record of the results I've collected and tried.

Apidemo Source to Com.example.android.apis.text.Link class, you can see the different effects of text.


First, the automatic application effect, using Android:autolink = "email|phone|web|map|all" property

<!--Text1 automatically linkifies things like URLs and phone numbers. --      <textview android:id= "@+id/text1"                android:layout_width= "match_parent"                android:layout_ height= "Match_parent"                android:paddingbottom= "8DP"                android:autolink= "all"                android:textappearance= "? Android:attr/textappearancemedium "                android:text=" @string/link_text_auto "                />

Click on the number, you will enter the dial-up page, click the URL, the browser will open the corresponding URL, click on the mailbox to enter the function of the email;


Ii. use of <a> tags in text

<string name= "link_text_manual" ><b>text2:explicit links using <a> markup.</b> this have      Markup for a <a href= ' http://www.google.com ' >link</a> specified      via an <a> tag.  Use a \ "Tel:\" URL to      <a href= "tel:4155551212" >dial a phone number</a>.    </string>

<!--Text2 uses a string resource containing explicit <a> tags to           specify links.--      <textview Android Oid:id= "@+id/text2"                android:layout_width= "match_parent"                android:layout_height= "Match_parent                " android:paddingtop= "8DP"                android:paddingbottom= "8DP"                android:textappearance= "android:attr/ Textappearancemedium "                android:text=" @string/link_text_manual "                />

    Text2 have links specified by putting <a> tags in the string        //resource.  By default these links would appear but not        //respond to user input.  To make them active, you need to        //Call Setmovementmethod () on the TextView object.        TextView t2 = (TextView) Findviewbyid (R.ID.TEXT2);        T2.setmovementmethod (Linkmovementmethod.getinstance ());


The third and the second are actually the same, except that the text is changed in JAVA code

Text3 shows creating text with links from HTML        in the Java//code, rather than from a string resource.  Note        that for a//fixed string with using a (localizable) resource as shown above        //is usually a better a-to go; t His example        was intended to//illustrate how do you might display text this came from a        //dynamic source (eg, the NE twork).        TextView t3 = (TextView) Findviewbyid (R.ID.TEXT3);        T3.settext (            html.fromhtml (                "<b>text3:constructed from Html programmatically.</b>  Text With a "+                " <a href=\ "http://www.google.com\" >link</a> "+                " created in the Java source code using HT ML. "));        T3.setmovementmethod (Linkmovementmethod.getinstance ());

Create rich effects by creating spanablestring strings and creating one or more spans on top of them.

Definition of spannablestring:

This was the class for text whose content was immutable but to which markup objects can be attached and detached. For mutable text, see Spannablestringbuilder.<span style= "color: #FF0000;" ><strong> translation:spannablestring</strong> is a class where text content cannot be changed, but tagged objects can be bound and unbound. </span>

The first half of the official document is well understood, and the latter half is not very well understood. Here's the problem:

    • What is a tagged object (markup objects)?
    • What does it mean to bind and unbind (attached and detached)?
Tag Object
Markup Language (also known as Markup language, tag language, flag language, identity language) is a combination of text and other text-related information, showing the structure of the document and data processing details of the computer text encoding. As for the tag object, it is a meaning to the markup language, which is the way to set the various styles of the text.

Examples are as follows:

Link_color is written in the following notation:

<?xml version= "1.0" encoding= "Utf-8"? ><selector xmlns:android= "http://schemas.android.com/apk/res/ Android ">    <item android:state_pressed=" true "          android:color=" #ffff00 "/> <!--pressed--    <item android:state_focused= "true"          android:color= "#ffff00"/> <!--focused--    <item Android:color= "#ff0000"/> <!--default--></selector>

The Java code is as follows:

TextView = (TextView) Findviewbyid (R.id.textview);//Use the Setspan (object what, int start, int end, int flags) method to set the Tag object,    The length of which is end-start. Use Removespan () to unbind a tagged object//public void Setspan (object what, int start, int end, int flags)//BIND specific Tag object (object what) from Starts at start, terminates to end of the text object (if the bound tag object is first removed)//Set Font Typefacespan ()//Set font size (absolute value) Absolutesizespan ()//Set font size (relative value) Relativesi Zespan ()//Set font size (relative value, multiple of default font width) Scalexspan ()//Set font foreground color Foregroundcolorspan ()//Set font background color Backgroundcolorspan ()/    /Set Font style Stylespan ()//Set underline Underlinespan ()//Strikethrough Strikethroughspan ()//superscript superscriptspan ()/Subscript Subscriptspan () Link Urlspan ()--Need to add Setmovementmethod method additional response//font appearance settings (including font name, font size, font style, font color, link color) textappearancespan ()//Bullets Bulletspan ()//Picture Imagespan ()//android.text.style.xxx get the parcel properties of various spans//create a Spannablestring Object MSP = new Spa                 Nnablestring ("Font test font size half twice times foreground background color normal bold italic bold italic underline strikethrough x1x2 phone mail website sms MMS map x Axis integrated/bot"); Set the font (DEFAULT,DEFAULT-BOLD,MONOSPACE,SERIF,SANs-serif) Msp.setspan (New Typefacespan ("Monospace"), 0, 2, spanned.span_exclusive_exclusive);                Msp.setspan (New Typefacespan ("serif"), 2, 4, spanned.span_exclusive_exclusive);       Set font size (absolute value, in pixels) msp.setspan (new Absolutesizespan, 4, 6, spanned.span_exclusive_exclusive);        The second parameter, Boolean dip, if true, indicates that the preceding font size is in dip, otherwise pixels, ditto.                  Msp.setspan (New Absolutesizespan (20,true), 6, 8, spanned.span_exclusive_exclusive); Sets the font size (relative value, units: pixels) parameter represents how many times the default font size Msp.setspan (new Relativesizespan (0.5f), 8, spanned.span_exclusive_exclusive  );  0.5f represents half of the default font size Msp.setspan (new Relativesizespan (2.0f), ten, spanned.span_exclusive_exclusive); 2.0f means twice times the default font size//Set font foreground color Msp.setspan (new Foregroundcolorspan (Color.magenta), X, Spanned.span  _exclusive_exclusive); Set foreground color to magenta//Set font background color Msp.setspan (new Backgroundcolorspan (Color.green), +, Spanned.span_exclusi  ve_exclusive); Set upBackground color cyan//Set font style normal, bold, italic, Bold italic Msp.setspan (new Stylespan (Android.graphics.Typeface.NORMAL), Max, Spanne  d.span_exclusive_exclusive);  Normal Msp.setspan (new Stylespan (Android.graphics.Typeface.BOLD), spanned.span_exclusive_exclusive);  Bold Msp.setspan (New Stylespan (Android.graphics.Typeface.ITALIC), N, spanned.span_exclusive_exclusive);  Italic Msp.setspan (New Stylespan (Android.graphics.Typeface.BOLD_ITALIC), spanned.span_exclusive_exclusive);        Coarse italic//Set underline Msp.setspan (new Underlinespan (), +, (spanned.span_exclusive_exclusive);                Set Strikethrough Msp.setspan (new Strikethroughspan (), +, spanned.span_exclusive_exclusive);     Set up the superscript msp.setspan (new Subscriptspan (), spanned.span_exclusive_exclusive, (+);   Subscript Msp.setspan (New Superscriptspan (), $, Notoginseng, spanned.span_exclusive_exclusive);        Superscript//hyperlink (need to add Setmovementmethod method additional response)Msp.setspan (New Urlspan ("tel:4155551212"), Panax Notoginseng, spanned.span_exclusive_exclusive);     Phone Msp.setspan (New Urlspan ("mailto:[email protected]"), (a), A-p, spanned.span_exclusive_exclusive);     E-mail Msp.setspan (new Urlspan ("http://www.baidu.com"), (a), spanned.span_exclusive_exclusive);     Network Msp.setspan ("sms:4155551212"), Urlspan, spanned.span_exclusive_exclusive);     SMS Using SMS: Or Smsto:msp.setSpan ("mms:4155551212"), Urlspan, spanned.span_exclusive_exclusive); MMS using MMS: or Mmsto:msp.setSpan (New Urlspan ("geo:38.899533,-77.036476"), +, +, spanned.span_exclusive_exclusive     ); Map//Set font size (relative value, units: pixels) The parameter is expressed as the default font width of how many times//2.0f represents twice times the default font width, that is, the x-axis direction is twice times the default font, and the height is constant msp.setspan                 (New Scalexspan (2.0f), spanned.span_exclusive_exclusive);        Set the font (including font name, font size, font style, font color, link color) colorstatelist csllink = null;        Colorstatelist CSL = null; XmlresOurceparser xppcolor=getresources (). GETXML (R.drawable.link_color);        try {csl= colorstatelist.createfromxml (getresources (), xppcolor);        csllink= Colorstatelist.createfromxml (Getresources (), xppcolor);            }catch (xmlpullparserexception e) {e.printstacktrace ();            }catch (IOException e) {e.printstacktrace (); } msp.setspan ("Monospace", Android.graphics.Typeface.BOLD_ITALIC, Textappearancespan, CSL, Csllink), 51, 53,                 spanned.span_exclusive_exclusive); Set Bullet Msp.setspan (new Bulletspan (android.text.style.bulletspan.contents_file_descriptor,color.red), 0, Msp.leng Th (), spanned.span_exclusive_exclusive); The first parameter represents the width that the bullet occupies, the second parameter is the color of the bullet//Set picture drawable drawable = Getresources (). Getdrawable (R.drawable.ic_launche         R);          Drawable.setbounds (0, 0, drawable.getintrinsicwidth (), Drawable.getintrinsicheight ()); Msp.setspan (New Imagespan (drawable),, Spanned.span_exclusive_exclusiVE);        Textview.settext (MSP);  Textview.setmovementmethod (Linkmovementmethod.getinstance ());

The effect is as follows:



Finally, there are a few points to note:

1) Many spans have Xxxspan (Parcel src) construction methods to get the Parcel properties of various spans in Android.text.style.XXX.XXX

2) Flags in Setspan (Object what, int start, int end, int flags) have several values:

Span_inclusive_exclusive (both front and rear included): [0,5]

Span_inclusive_inclusive (previously included, not included): [0,5]

Span_exclusive_exclusive (not included before and after):(0,5)

Span_exclusive_inclusive (not previously included, including later):(0,5]

3) When using Textappearancespan, color must be a selector type.

/**     * makes text is drawn with the specified typeface, size, style,     * and colors.     *    /Public Textappearancespan (String family, int style, int size,                              colorstatelist color, colorstatelist linkcolor ) {        mtypeface = family;        Mstyle = style;        mtextsize = size;        Mtextcolor = color;        Mtextcolorlink = LinkColor;    }


TextView Spnnable used in Android

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.