Android使用TextView实现无下划线超链接

转于:http://orgcent.com/android-textview-no-underline-hyperlink/

----------------------------------------------------------------------------------------------

Android系统默认把网址、电话、地图(geo地址)、邮箱等转换为超链接。
具体请查看android:TextView设置文本样式和超链接

和HTML中的一样,默认超链接都带下划线的,下面的方案可以在TextView中去掉超链接的下划线:

1、重写ClickableSpan类来去掉下划线样式(系统默认使用ClickableSpan来封装超链接)

//无下划线超链接,使用textColorLink、textColorHighlight分别修改超链接前景色和按下时的颜色
private  class NoLineClickSpan  extends ClickableSpan  { 
     String text ;

     public NoLineClickSpan ( String text )  {
         super ( ) ;
         this. text  = text ;
     }

    @Override
     public  void updateDrawState (TextPaint ds )  {
        ds. setColor (ds. linkColor ) ;
        ds. setUnderlineText ( false ) ;  <span style = "color: red;" > //去掉下划线</span>
     }

    @Override
     public  void onClick ( View widget )  { 
        processHyperLinkClick (text ) ;  <span style = "color: red;" > //点击超链接时调用</span>
     }
}


2、把超链接文本封装为NoLineClickSpan对象,并添加到TextView中

TextView tv  = findViewById (R. id. tv_click ) ;
SpannableString spStr  =  new SpannableString ( "萝卜白菜博客--&gt;http://orgcent.com" ) ;
ClickSpan clickSpan  =  new NoLineClickSpan (vo ) ;  //设置超链接
spStr. setSpan (clickSpan,  0, str. length ( ), Spanned. SPAN_INCLUSIVE_EXCLUSIVE ) ;
tv. append (spStr ) ;
tv. setMovementMethod (LinkMovementMethod. getInstance ( ) ) ;

PS:不用把TextView的属性autoLink设为”all”.

3、设置超链接为可点击状态

tv. setMovementMethod (LinkMovementMethod. getInstance ( ) ) ;

PS:在NoLineClickSpan类中实现onClick()回调方法.

猜你喜欢

转载自yuemeiqing2008-163-com.iteye.com/blog/2148379