Android TextView 添加下划線的幾種方式


總結起來大概有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來格式部分字符串。
 
 
如果是在資源文件里:
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

看完的順手點歌贊唄,謝謝鼓勵!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM