您的位置:首页 > 移动开发 > Android开发

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

2016-02-15 20:00 459 查看
原文链接:https://www.geek-share.com/detail/2666537601.html 总结起来大概有5种做法: 
1. 将要处理的文字写到一个资源文件,如string.xml(使用html用法格式化)   2. 当文字中出现URL、E-mail、电话号码等的时候,可以将TextView的android:autoLink属性设置为相应的的值,如果是所有的类型都出来就是android:autoLink="all",当然也可以在java代码里 做,textView01.setAutoLinkMask(Linkify.ALL);    3. 用Html类的fromHtml()方法格式化要放到TextView里的文字 ,与第1种一样,只是是用代码动态设置   4. 设置TextView的Paint属性:tvTest.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG ); //下划线
5. 用Spannable或实现它的类,如SpannableString来格式部分字符串。    另外附上一篇博客介绍:Android TextView中文字通过SpannableString来设置超链接、颜色、字体等属性     如果是在资源文件里: 1、字符串资源中设置下划线属性
<resources>
<string name="hello"><u>phone:0123456</u></string>
<string name="app_name">MyLink</string>
</resources>
直接让TextView引用字符串资源的name即可。

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"  />

 

如果是代码里:
1、使用Html.fromHtml()
TextView textView = (TextView)findViewById(R.id.tv_test);
textView.setText(Html.fromHtml("<u>"+"0123456"+"</u>"));

2、使用TextView的Paint的属性
tvTest.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
tvTest.getPaint().setAntiAlias(true);//抗锯齿

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);

}

另外一篇文章中有几个具体的实例可以参考:
http://hunankeda110.iteye.com/blog/1420470

看完的顺手点歌赞呗,谢谢鼓励!

转载于:https://www.cnblogs.com/popfisher/p/5191242.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: