Android Learning note-textview (text box) (ii)

Source: Internet
Author: User

Article reference from: http://www.runoob.com/w3cnote/android-tutorial-textview.html

2.4 Using the Autolink property to identify link types

When the text appears in the Url,e-mail, phone number, map, we can set the Autolink property, when we click on the text in the corresponding section, you can jump to a default app, such as a bunch of numbers, click to jump to the dial screen!

All is all included, automatic recognition protocol header ~ setautolinkmask (linkify.all) can be called in Java code; This time can not write the protocol header, Autolink will be automatically recognized, but also for this TextView set: Setmovementmethod (Linkmovementmethod.getinstance ()); Otherwise the click is no effect!

2.5 TextView Play HTML

Title, in addition to displaying ordinary text, TextView also pre-defined some HTML-like tags, through which we can make TextView display different font color, size, font, even display pictures, or links, etc.! As long as we use some HTML tags, plus Android.text.HTML class support, you can do the above functions!

PS: Of course, not all tags are supported, commonly used are the following:

  • <font: Set colors and fonts.
  • <big;: Setting the font size
  • <small;: Setting the Font s
  • <i><b;: Italic Bold
  • <a;: Connection URL
  • <img;: image

If the direct settext is not useful, we need to call the Html.fromhtml () method to convert the string to the Charsequence interface, and then set it, if we need to set the corresponding, to set the TextView, call the following method:Java setMovementMethod(LinkMovementMethod.getInstance())

Well, then we'll write the code to try it out:

1) Test text and hyperlink tags

 PackageJay.com.example.textviewdemo;ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;Importandroid.text.Html;ImportAndroid.text.method.LinkMovementMethod;Importandroid.text.util.Linkify;ImportAndroid.widget.TextView; Public classMainactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); TextView T1=(TextView) Findviewbyid (R.id.txtone); String S1= "<font color= ' Blue ' ><b> Baidu a bit, you know ~:</b></font><br>"; S1+ = "<a href = ' http://www.baidu.com ' > Baidu </a>";        T1.settext (html.fromhtml (S1));    T1.setmovementmethod (Linkmovementmethod.getinstance ()); }}

2) test src tag, insert Picture:

Look at the run:

Next look at the implementation of the Code, the implementation of the code looks a bit complicated, using the reflection (right, don't forget to drop an icon in the drawable directory of the picture Oh!). ):

 Public classMainactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); TextView T1=(TextView) Findviewbyid (R.id.txtone); String S1= "Picture: <br>"; T1.settext (html.fromhtml (S1,NewHtml.imagegetter () {@Override Publicdrawable getdrawable (String source) {drawable Draw=NULL; Try{Field field= R.drawable.class. GetField (source); intResourceId = Integer.parseint (Field.get (NULL). toString ()); Draw=getresources (). getdrawable (ResourceId); Draw.setbounds (0, 0, Draw.getintrinsicwidth (), Draw.getintrinsicheight ()); } Catch(Exception e) {e.printstacktrace (); }                returnDraw; }        }, NULL)); }}
2.6 Spannablestring&spannablestringbuilder Custom Text

In addition to the above HTML can be customized to our TextView style, you can also use spannablestring and Spannablestringbuilder to complete, the difference: The former is for the immutable text, while the latter is for the variable text

1) The simplest example: run:

Implementation code:

 Public classMainactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); TextView T1=(TextView) Findviewbyid (R.id.txtone); TextView T2=(TextView) Findviewbyid (r.id.txttwo); Spannablestring span=NewSpannablestring ("Red call italics strikethrough green underline Picture:.")); //1. Set the background color, Setspan need to specify the flag,spanned.span_exclusive_exclusive (not included before and after)Span.setspan (NewForegroundcolorspan (color.red), 0, 2, spanned.span_exclusive_exclusive); //2. Marking text with hyperlinksSpan.setspan (NewUrlspan ("tel:4155551212"), 2, 5, spanned.span_exclusive_exclusive); //3. Mark text with Style (italic)Span.setspan (NewStylespan (Typeface.bold_italic), 5, 7, spanned.span_exclusive_exclusive); //4. Use strikethrough to mark textSpan.setspan (NewStrikethroughspan (), 7, 10, spanned.span_exclusive_exclusive); //5. Mark the text with an underscoreSpan.setspan (NewUnderlinespan (), 10, 16, spanned.span_exclusive_exclusive); //6. Mark with colorSpan.setspan (NewForegroundcolorspan (Color.green), 10, 13, spanned.span_exclusive_exclusive); //7.//Get drawable Resourcesdrawable d =getresources (). getdrawable (R.drawable.icon); D.setbounds (0, 0, D.getintrinsicwidth (), D.getintrinsicheight ()); //8. Create a Imagespan and replace the text with ImagespanImagespan Imgspan =NewImagespan (d, Imagespan.align_baseline); Span.setspan (Imgspan,18, 19, spannable.span_inclusive_exclusive);    T1.settext (span); }}

2) realize some clickable TextView believe that the friends who have played QQ space and friends on the following things are not unfamiliar with it, we can click the corresponding users and then access to view user-related information is it!

Let's write a simple example to achieve the effect:

 Public classMainactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); TextView T1=(TextView) Findviewbyid (R.id.txtone); StringBuilder SB=NewStringBuilder ();  for(inti = 0; I < 20; i++) {sb.append ("Friends" + i + ","); } String likeusers= sb.substring (0, Sb.lastindexof (",") . toString ();        T1.setmovementmethod (Linkmovementmethod.getinstance ());    T1.settext (Addclickpart (likeusers), TextView.BufferType.SPANNABLE); }    //define a single-click processing method for each part of the text    Privatespannablestringbuilder Addclickpart (String str) {//like the icon, there is no material, just find a smiley face instead of the next ~Imagespan Imgspan =NewImagespan (mainactivity. This, R.drawable.ic_widget_face); Spannablestring Spanstr=NewSpannablestring ("P.")); Spanstr.setspan (Imgspan,0, 1, spannable.span_inclusive_exclusive); //creates a Spannablestringbuilder object that joins multiple stringsSpannablestringbuilder SSB =NewSpannablestringbuilder (SPANSTR);        Ssb.append (str); String[] Likeusers= Str.split (","); if(Likeusers.length > 0) {             for(inti = 0; i < likeusers.length; i++) {                FinalString name =Likeusers[i]; Final intStart = Str.indexof (name) +spanstr.length (); Ssb.setspan (NewClickablespan () {@Override Public voidOnClick (View widget) {toast.maketext (mainactivity. This, Name, Toast.length_short). Show (); } @Override Public voidupdatedrawstate (textpaint ds) {Super. Updatedrawstate (DS); //remove underline, set font color to blueDs.setcolor (Color.Blue); Ds.setunderlinetext (false); }},start,start+ name.length (), 0); }        }    returnSsb.append ("et" + likeusers.length + "personal feel great"); }}

Run:

The core is actually: Clickablespan's setup just ~

2.7 TextView to realize the effect of the marquee

Realize:

Code implementation:

<TextViewAndroid:id= "@+id/txtone"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"android:textsize= "18SP"Android:singleline= "true"android:ellipsize= "Marquee"Android:marqueerepeatlimit= "Marquee_forever"android:focusable= "true"Android:focusableintouchmode= "true"Android:text= "You say all day Dog Day dog, but you did not come, ha ha ha ha ha hehe ~"/>
2.8 Set TextView word spacing and line spacing

Just as we usually write documents, we need to layout, set the line or the spacing between the words: Android TextView can also make such a setting:

Word spacing:

Android:textscalex: Controls the font horizontal orientation of the zoom, the default value is 1.0f, the value is float in Java Setscalex( 2.0f);           

Line spacing: In Android, TextView is relatively compact by default in Chinese, in order to keep line spacing for each line

Android:linespacingextra: set line spacing, such as "3DP" android:linespacingmultiplier: sets a multiple of the line spacing, such as "1.2"

The Java code can be set by: setlinespacing method

2.9 Automatic Line Wrapping

Line wrap is set by Android:singleline , which defaults to false.

If you need to wrap a line, you can use:

Android:="false"  

If you want to show up on one line without wrapping, you can use:

Android:="true"  

In addition, you can also set the multi-line display, add a Maxlines properties can!

Android Learning Note-textview (text box) (b)

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.