当前位置: 移动技术网 > 移动技术>移动开发>Android > Android TextView 添加下划线的几种方式:总结其中的5种做法

Android TextView 添加下划线的几种方式:总结其中的5种做法

2020年08月01日  | 移动技术网移动技术  | 我要评论
1、在字符串资源中设置下划线属性直接让TextView引用字符串资源的name即可。<resources> <string name="hello"><u>phone:0123456</u></string> <string name="app_name">MyLink</string></resources>2、TextView设置autoLink属性<TextView xml

1、在字符串资源中设置下划线属性

直接让TextView引用字符串资源的name即可。

<resources>
    <string name="hello"><u>phone:0123456</u></string>
    <string name="app_name">MyLink</string>
</resources>

2、TextView设置autoLink属性

<TextView xmlns:android="http://schemas.android.com/apk/res/android"  
     android:id="@+id/text1"
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     android:autoLink="all"  
     android:text="@string/link_text_auto"  />  

3、Java代码里使用

3-1.Html.fromHtml()

TextView textView = (TextView)findViewById(R.id.tv_test); 
textView.setText(Html.fromHtml("<u>"+"0123456"+"</u>"));

3-2、使用TextView的Paint的属性

tvTest.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
tvTest.getPaint().setAntiAlias(true);//抗锯齿

3-3、使用SpannableString类

SpannableString content = new SpannableString(str);
content.setSpan(new UnderLineSpan, 0, str.length(), 0);

代码里面自定义超链接样式:

TextView tv=new TextView(this);
tv.setText(Html.fromHtml("<a href=\"http://blog.csdn.net/CAIYUNFREEDOM\">自定义的超链接样式</a>"));
// 在单击链接时凡是有要执行的动作,都必须设置MovementMethod对象
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){     
          URLSpan myURLSpan=   new  URLSpan(url.getURL());                        
          style.setSpan(myURLSpan,sp.getSpanStart(url),sp.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
          style.setSpan(new ForegroundColorSpan(0xFFFF0000), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);//设置前景色为红色
    }  
   tv.setText(style);  
}

本文地址:https://blog.csdn.net/weixin_43825473/article/details/108167283

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网