Usually we only need to use TextView to display the text information, display to the user to see, and click the corresponding listener event to the button and other controls to deal with, of course, TextView can also implement the Click event. Sometimes we have to click on some of the text in TextView, what should we do? There are generally the following three ways:
1, set the Android:autolink property of TextView in the layout file, such as setting android:autolink= "Phone", you can make a direct call by clicking on the phone number. Android:autolink Sets whether text is displayed as a clickable link when the text is a URL link/email/phone number/map. Optional values (None/web/email/phone/map/all), and so on. This is the simplest, but the goal to achieve is relatively simple, such as only can call or send e-mail and so on.
2, use the HREF chain in HTML format, for example:
String content= "<font color= #ff0000 > click on the corresponding text to jump to the Web page" + "</font><a href= ' http://www.baidu.com ' > Baidu </a> "; TextView linktextview= (TextView) Findviewbyid (R.id.linktextview);Textview.settext (html.fromhtml (content));
Click on the above Baidu two words can jump directly to Baidu Web page. This way generally can only jump to the Web page.
3, when we want to achieve the click of the text to jump to the specified page or achieve a specific effect (such as pop-up dialog box, toast information, etc.) we can use spannablestring to achieve:
TextView textview= (TextView) Findviewbyid (r.id.tv);
spannablestring spanstr = new Spannablestring (Textview.gettext (). toString ()); Nounderlinespan Mnounderlinespan = new Nounderlinespan ();//The purpose of this sentence is to remove the special text underline effect Spanstr.setspan (New Foregroundcolorspan (Color.parsecolor ("#00b5f0")), S.length ()-7, S.length (), spannable.span_exclusive_inclusive);//Set some text text color, here the text length must be greater than 7 .S.setspan (New Clickablespan () {
@Overridepublic void OnClick (View widget) { //This is the click event to achieve your desired effect }}, Spanstr.length ()-7, S.length (), Spanned.span_mark_mark); Spanstr.setspan (Mnounderlinespan, Spanstr.length ()-7, Spanstr.length (), Spannable.span_exclusive_ INCLUSIVE);Textview.settext (SPANSTR); Textview.setmovementmethod (Linkmovementmethod.getinstance ());
To implement the clear text underline:
Public class Nounderlinespan extends Underlinespan {
@Overridepublic void Updatedrawstate (Textpaint ds) { Ds.setcolor (ds.linkcolor); Ds.setunderlinetext (false); }}
Of course there are other ways!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android implements partial text listener events in TextView