Android Development Note-Personalized TextView (Sina Weibo)

Source: Internet
Author: User

These days in the imitation of Sina Weibo client, in the processing of micro-blog information need to deal with the keyword highlighting and Weibo expression, check some information, decided to record something

First look at the following:

Like the above # topic #, @XXX nickname, HTTP: Web links and other elements, in the micro-Borrie is highlighted as a blue effect.

So how should we dynamically implement these effects in our Android program development?

Actually very simple, I wrote a small example, first look at:

In fact, to achieve this effect is very simple, in Android has helped us to encapsulate a series of tools, such as:




Spannablestring and Spannablestringbuilder can be used to set different spans, can easily be personalized textview, such as bold, italic, foreground color, background color, font size, font style and so on, A number of span types are defined in* to be used.

In fact, there is nothing to say, this is just a tool class, only need to master his general use of the method can be, here directly on the code (annotated)

1  Packagecom.example.spannabletest;2 3 ImportJava.util.HashMap;4 ImportJava.util.Map;5 ImportJava.util.regex.Matcher;6 ImportJava.util.regex.Pattern;7 8;9;Ten; One ImportAndroid.os.Bundle; A Importandroid.text.SpannableString; - Importandroid.text.Spanned; -; the; -; - ImportAndroid.widget.TextView; -  +  Public classMainactivityextendsActivity { -      +     PrivateTextView TextView; A  at     //string to convert -     PrivateString info= "#我爱JAVA # my Weibo name: @Balla_ rabbit [Rabbit]]; -  - @Override -     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); in Setcontentview (r.layout.activity_main); -textview=(TextView) Findviewbyid (R.ID.TX); to          +          -          the          *         /** $ * There are many tools for personalizing TextView content on Android, which can be used instead of regular string. Panax Notoginseng * android.text.Spanned - * android.text.SpannableString the * Android.text.SpannableStringBuilder +          *  A * Since the Spannable class finally implements the Charsequence interface, it is possible to direct spannablestring and Spannablestringbuilder through Textview.settext () Set to TextView.  the          */ +          -         //instantiate a Spannable object $Spannablestring spannablestring=Newspannablestring (info); $         //Use the Setspan () method to define different style content -         //Set Font -         //mode one: direct positioning theSpannablestring.setspan (NewForegroundcolorspan (Color.Blue), 0, 8, spanned.span_exclusive_exclusive); -         //mode two: matching string tool class positioningWuyiSpannablestring.setspan (NewForegroundcolorspan (Color.Blue), Info.indexof ("@"), Info.indexof (""), spanned.span_exclusive_exclusive); the         //method Three, using regular expression to match the positioning -Map<string,integer> map=gethttppostion (); WuSpannablestring.setspan (NewForegroundcolorspan (Color.Blue), Map.get ("Start"), Map.get ("End"), spanned.span_exclusive_exclusive); -          About         //Set Font size $Spannablestring.setspan (NewRelativesizespan ((float) 1.5, Map.get ("Start")), Info.length (), spanned.span_exclusive_exclusive); -         //Set Picture Emoticons -Drawable drawable=getresources (). getdrawable (R.drawable.d_tuzi); -Drawable.setbounds (0, 0, Drawable.getintrinsicwidth (), Drawable.getintrinsicheight ()); ASpannablestring.setspan (NewImagespan (drawable), Info.indexof ("["), Info.indexof ("]") +1, spanned.span_inclusive_inclusive); +          the          - Textview.settext (spannablestring);  $          the          the     } the      the      PublicMap<string,integer>gethttppostion () { -Map<string,integer> map=NewHashmap<string,integer>(); inPattern pattern=pattern.compile ("http:.*"); theMatcher matcher=Pattern.matcher (info); the         if(Matcher.find ()) { AboutMap.put ("Start", Matcher.start ()); theMap.put ("End", Matcher.end ()); the         } the         returnmap; +          -     } the Bayi  the  the  -}

How to use:

1, to use personalized textview, we need to create a spannablestring or Spannablestringbuilder, the difference is that spannablestring like a string, A string is passed in when the object is constructed, and then the contents of the string cannot be changed, and multiple spannablestring cannot be spliced, while the Spannablestringbuilder is more like StringBuilder. It can use its append () method to stitch multiple strings.

Spannablestring class:

Spannablestringbuffer class:

2. After you have created the Spannable objects, you can set span for them to achieve the desired personalization (both spannablestring and Spannablestringbuilder have an identical span method)

Here is the API:

Parameter one: Object what (here refers to the style)

Absolutesizespan (int size): Sets the font size, which is an absolute value, equivalent to the font size in Word.

Relativesizespan (float proportion): Sets the font size, and the argument is a multiple of the default font size.

Scalexspan (float proportion): Scaled font, similar to the above, the default is 1, set is the original multiplied by proportion, greater than 1 o'clock magnification (zoon in), smaller than when zoomed out (zoom out).

Backgroundcolorspan (int color): Background coloring, parameters are color values, you can directly use the constants defined in, or with COLOR.RGB (int, int, int).

Foregroundcolorspan (int color): foreground shading, which is the coloring of words, with parameters consistent with 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 defined constants, 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, it is common to use only the construction parameters described above, you do not need to set other properties, and if necessary, you can also set other properties, see the API documentation for details .

Parameters Two and three: (int start,int end)

Here is the location of the personalization match: There are many ways to achieve, such as direct write dead position, can also be used with some methods of the string class, such as: IndexOf (), can also write a regular matching method, if you want to match the match can be stored in a map collection, the case, According to your own project choice ha.

Parameter four: (int flags)

Commonly used are: (This is understood as a mathematical interval definition, open or closed interval)

Spanned.span_exclusive_exclusive---does not contain endpoints where both start and end are located

Spanned.span_exclusive_inclusive---does not contain end start, but contains the endpoint where end

Spanned.span_inclusive_exclusive---Contains both ends of start, but does not contain the endpoint where end

Spanned.span_inclusive_inclusive---contains endpoints where both start and end are located

There are some other attributes that are not listed here, so let's go through the API documentation.

Again to look at the source of spannablestring and Spannablestringbuffer, we can find that they have implemented the Charsequence interface, so they can directly in the Textview.settext () set

All right

Android Development Note-Personalized TextView (Sina Weibo)

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