Android TextView 添加下划线的几种方式

2022-08-05  本文已影响0人  APP福星高照

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 >自定义的超链接样式</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);  
}
上一篇下一篇

猜你喜欢

热点阅读