A study of Android TextView

Source: Internet
Author: User

1: Insert Picture substitution

Code Msubjectdetailview = (TextView) Findviewbyid (R.id.subject_detail);        Charsequence Text = "★,dsfdsfdddd, if fdsfs★ dongdong";        Spannablestringbuilder builder = new Spannablestringbuilder (text);        String rexgstring = "★";        Pattern pattern = pattern.compile (rexgstring);        Matcher Matcher = pattern.matcher (text); while (Matcher.find ()) {Builder.setspan (new Imagespan (this, r.drawable.ic_launcher), match        Er.start (), Matcher end (), spannable.span_exclusive_exclusive); } msubjectdetailview.settext (builder);//Layout file <relativelayout xmlns:android= "Http://schemas.android.com/apk/res /android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_parent "Android:layout_heigh t= "Match_parent" tools:context= ". Mainactivity "> <textview android:id=" @+id/my_title "android:layout_width=" Wrap_content "and Roid:layout_height= "Wrap_conteNT "android:layout_centerhorizontal=" true "android:layout_centervertical=" true "android:text=" @string /hello_world "/> <textviewandroid:id=" @+id/subject_detail "android:layout_width=" Match_parent "Android: layout_height= "Wrap_content" android:minheight= "50DP" android:gravity= "center_vertical" android:text= "Subject" Android:textcolor= "@android: Color/primary_text_light_nodisable" android:background= "@android: Color/white" Android:textsize= "25SP"/></relativelayout>

2: Add a picture to another TextView

     Public voidsetchips () {if(GetText (). ToString (). Contains (","))//check Comman in string{Spannablestringbuilder SSB=NewSpannablestringbuilder (GetText ()); //split string wich commaString chips[] = GetText (). toString (). Trim (). Split (","); intX =0; //Loop would generate Imagespan for every country name separated by comma             for(String c:chips) {//Inflate Chips_edittext layoutLayoutinflater LF =(Layoutinflater) GetContext (). Getsystemservice (Activity.layout_inflater_service); TextView TextView= (TextView) lf.inflate (R.layout.chips_edittext,NULL); Textview.settext (c); //Set Text                intImage =( (Chipsadapter) Getadapter ()). GetImage (c); Textview.setcompounddrawableswithintrinsicbounds (0, 0, image, 0); //capture bitmapt of genreated TextView                intSpec = Measurespec.makemeasurespec (0, measurespec.unspecified);                Textview.measure (spec, spec); Textview.layout (0, 0, Textview.getmeasuredwidth (), Textview.getmeasuredheight ()); Bitmap b=Bitmap.createbitmap (Textview.getwidth (), Textview.getheight (), Bitmap.Config.ARGB_8888); Canvas Canvas=NewCanvas (b); Canvas.translate (-TEXTVIEW.GETSCROLLX (),-textview.getscrolly ());                Textview.draw (canvas); Textview.setdrawingcacheenabled (true); Bitmap cachebmp=Textview.getdrawingcache (); Bitmap viewbmp= Cachebmp.copy (Bitmap.Config.ARGB_8888,true);  Textview.destroydrawingcache (); //destory drawable//Create bitmap drawable for ImagespanBitmapdrawable bmpdrawable =Newbitmapdrawable (viewbmp); Bmpdrawable.setbounds (0, 0, Bmpdrawable.getintrinsicwidth (), Bmpdrawable.getintrinsicheight ()); //Create and set ImagespanSsb.setspan (NewImagespan (bmpdrawable), X, X +c.length (), spannable.span_exclusive_exclusive); X= x+ C.length () +1; }            //Set chips spanSetText (SSB); //move cursor to lastsetselection (GetText (). Length ()); }                    }

3:android Spannablestringbuilder realization of the picture and text mixed row

spannablestringbuilder Usage Explanation: spannablestring SS=NewSpannablestring ("Red call italics strikethrough green underline Picture:.")); //mark text with colorSs.setspan (NewForegroundcolorspan (color.red), 0, 2,                       //Setspan required flag,spanned.span_exclusive_exclusive (not included before and after).spanned.span_exclusive_exclusive); //mark text with a hyperlinkSs.setspan (NewUrlspan ("tel:4155551212"), 2, 5, spanned.span_exclusive_exclusive); //mark text with style (italic)Ss.setspan (NewStylespan (Typeface.bold_italic), 5, 7, spanned.span_exclusive_exclusive); //mark text with strikethroughSs.setspan (NewStrikethroughspan (), 7, 10, spanned.span_exclusive_exclusive); //mark text with an underscoreSs.setspan (NewUnderlinespan (), 10, 16, spanned.span_exclusive_exclusive); //mark with colorSs.setspan (NewForegroundcolorspan (Color.green), 10, 13, spanned.span_exclusive_exclusive); //Get drawable Resourcesdrawable d =getresources (). getdrawable (R.drawable.icon); D.setbounds (0, 0, D.getintrinsicwidth (), D.getintrinsicheight ()); //Create ImagespanImagespan span =NewImagespan (d, Imagespan.align_baseline); //Replace text with ImagespanSs.setspan (span, 18, 19, spannable.span_inclusive_exclusive);             Txtinfo.settext (ss); Txtinfo.setmovementmethod (Linkmovementmethod.getinstance ()); //implementing scrolling of textusually used to display text, but sometimes also need to be in the text with some pictures, such as QQ can use emoticons, such as the need for text highlighting and so on, how to do so in Android?     Remember that there is a Android.text package in Android, which provides powerful handling of the text. Add pictures mainly with spannablestring and Imagespan class: Drawable drawable=getresources (). getdrawable (ID); Drawable.setbounds (0, 0, Drawable.getintrinsicwidth (), Drawable.getintrinsicheight ()); //The text that needs to be processed, [smile] is the text that needs to be substitutedSpannablestring spannable =NewSpannablestring (GetText (). toString () + "[Smile]"); //to replace the specified text with a picture, you need to use ImagespanImagespan span =NewImagespan (drawable, imagespan.align_baseline); //start replacing, note that the 2nd and 3rd parameters indicate where to start replacing where to replace end (start and end)//The last parameter is similar to a set in mathematics, [5,12] represents 5 to 12, including 5 but excludingSpannable.setspan (span, GetText (). Length (), GetText (). Length () + "[Smile]". Length (), spannable.span_inclusive_exclusive);  SetText (spannable); 
highlight the text you want: Public voidHighlightintStartintend) {Spannablestringbuilder spannable=NewSpannablestringbuilder (GetText (). toString ());//for variable stringsForegroundcolorspan span=NewForegroundcolorspan (color.red);              Spannable.setspan (span, start, end, spannable.span_exclusive_exclusive);          SetText (spannable); Add an underscore: Public voidUnderline (intStartintend) {Spannablestringbuilder spannable=NewSpannablestringbuilder (GetText (). toString ()); Characterstyle span=NewUnderlinespan ();              Spannable.setspan (span, start, end, spannable.span_exclusive_exclusive);          SetText (spannable); } Combined use: Spannablestringbuilder spannable=NewSpannablestringbuilder (GetText (). toString ()); Characterstyle span_1=NewStylespan (Android.graphics.Typeface.ITALIC); Characterstyle span_2=NewForegroundcolorspan (color.red);              Spannable.setspan (span_1, start, end, spannable.span_exclusive_exclusive);              Spannable.setspan (span_2, start, end, spannable.span_exclusive_exclusive);  SetText (spannable); 
case: A string with \ n line break can display 2 colors in this method/*** string with \ n line break can display 2 colors in this method *@paramtext *@paramColor1 *@paramColor2 *@return          */          PublicSpannablestringbuilder Highlight (String text,intColor1,intColor2,intfontSize) {Spannablestringbuilder spannable=NewSpannablestringbuilder (text);//for variable stringsCharacterstyle span_0=NULL, span_1=NULL, span_2; intEnd=text.indexof ("\ n"); if(End==-1) {//Use the first color if there is no line breakspan_0=NewForegroundcolorspan (Color1); Spannable.setspan (Span_0,0, Text.length (), spannable.span_exclusive_exclusive); }Else{span_0=NewForegroundcolorspan (Color1); Span_1=NewForegroundcolorspan (COLOR2); Spannable.setspan (Span_0,0, end, spannable.span_exclusive_exclusive); Spannable.setspan (span_1, End+1, Text.length (), spannable.span_exclusive_exclusive); Span_2=NewAbsolutesizespan (fontSize);//Font SizeSpannable.setspan (Span_2, end+1, Text.length (), spannable.span_exclusive_exclusive); }              returnspannable; }

The relevant methods used:

1:textview.setcompounddrawableswithintrinsicbounds (0, 0, image, 0);


 Public voidSetcompounddrawableswithintrinsicbounds (intLeftintTopintRightintbottom) {        FinalResources Resources =GetContext (). Getresources (); Setcompounddrawableswithintrinsicbounds ( Left! = 0? Resources.getdrawable (left):NULL, Top! = 0? Resources.getdrawable (top):NULL, Right! = 0? Resources.getdrawable (right):NULL, Bottom! = 0? Resources.getdrawable (bottom):NULL); }

2:ssb.setspan (New Imagespan (bmpdrawable), x, X + c.length (), spannable.span_exclusive_exclusive);//position where obj is inserted

A study of Android TextView

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.