An encapsulation class that implements click Text Hyperlinks (no underscores) in Android TextView

Source: Internet
Author: User

There are some times in Android where you need to set up hyperlinks on TextView, and do something when you click on those hyperlinks. For example, some keyword on Sina Weibo will jump to the corresponding page when clicked.


How to achieve our direct look at the source code it.

/** * *created by Mr.simple, 6:00pm, 20141:51:40 PM. *copyright (c), hehonghui@umeng.com All rights Reserved.                                                   * *                ##################################################### *                #                      # # # # # # # _oo0oo_ # # O8888888O # * # 88 ". "88 # * # (|                    -_- |) # * # 0\ =/0 # * # ___/'---     ' \___ # * #. ' \\|                 |# '.  # *                #                 / \\||| :  ||| # \                # *                #                / _||||| -:- |||||   - \              # *                #               | |   \\\  -  #/ |              |       # *                #        |  \_|             ' \---/' |_/| # * # \ .-\__ ‘-‘ ___/-. / # * # ___‘.  .‘ /--.--\  `. .‘ ___           # *                #          .""         ' < '. ___\_<|>_/___. ' > ' ". # *                #         | | :  `- \`.; `\ _ /`;.       `/ - ` : | |   # *                #         \  \ `_.                        \_ __\/__ _/.-'//# * # ===== '-.____ '. ___ \_____/___.-' ___.-' ===== # * #   ' =---= ' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # # # # # # # # # # # # # # Buddha Bless Forever # UG # * # # * ################ ##################################### */package Com.umeng.community.utils;import Android.content.Context;import Android.text.html;imPort Android.text.spannable;import Android.text.spannablestringbuilder;import Android.text.textpaint;import Android.text.method.linkmovementmethod;import Android.text.style.clickablespan;import Android.text.style.URLSpan    Import android.widget.textview;/** * @author mrsimple */public abstract class Topicspanwrapper extends Clickablespan {    protected Context Mcontext;    protected TextView Mtextview;  /** * @param context * @param TV */Public Topicspanwrapper (context context, TextView TV) {Mcontext        = Context;        Mtextview = TV;    Updateclickspan (TV); }/** * Update span * * @param RV */public void Updateclickspan (TextView TV) {//Here splicing hyperlinks, I add in front and back        A well number, you can remove String Htmllinktext = "<a href=" here to fill in a URL ' ># ' + tv.gettext (). toString () + "#</a>";        Tv.settext (html.fromhtml (Htmllinktext));        Tv.setmovementmethod (Linkmovementmethod.getinstance ());        Charsequence text = Tv.gettext (); if (text instanceof spannable) {int end = Text.length ();            Spannable sp = (spannable) tv.gettext ();            urlspan[] urls = Sp.getspans (0, end, Urlspan.class);            Spannablestringbuilder style = new Spannablestringbuilder (text); Style.clearspans (); Should clear old spans for (Urlspan url:urls) {//Set span Style.setspan (this            , Sp.getspanstart (URL), sp.getspanend (URL), spannable.span_exclusive_exclusive);        } tv.settext (style);        }} @Override public void Updatedrawstate (Textpaint ds) {super.updatedrawstate (DS);    Remove the underline Ds.setunderlinetext (false) of the hyperlink; }}

Use the Demo sample:

public class Userinfoactivity extends Fragmentactivity implements Onclicklistener {Fragmentmanager Mfragmentman;    Private TextView Musernametv; /* * (non-javadoc) * @see android.app.activity#oncreate (android.os.Bundle) */@Override protected void O        Ncreate (Bundle savedinstancestate) {requestwindowfeature (window.feature_no_title);        Super.oncreate (savedinstancestate);        Setcontentview (R.layout.umeng_comm_user_info);    Inituicomponents ();        }/** * */private void inituicomponents () {Mfragmentman = Getsupportfragmentmanager ();        Mpostedfragment = new Postedfragment ();                        Mfragmentman. BeginTransaction (). Add (R.id.user_info_fragment_container, Mpostedfragment,        PostedFragment.class.getSimpleName ()). commit ();        Layout is not given, in short User_name_tv is a TextView Musernametv = (TextView) Findviewbyid (R.ID.USER_NAME_TV); /** * Wrap text in TextView as clickableHyperlink */New Topicspanwrapper (this, Musernametv) {@Override the public void OnClick (View            Widget) {Toast.maketext (Mcontext, "clicked Hyperlink text", Toast.length_short). Show ();         }        }; }}

Effect:


Click later




The text of the toast in the picture and the code is inconsistent, because the text is written in the text of my demo is not the same, directly ignore the problem can be.


An encapsulation class that implements click Text Hyperlinks (no underscores) in Android TextView

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.