Android TextView設置下劃線

最近總是遇到Textview加下劃線,所以抽空總結一下

Android TextView加下劃線的方法大概有五種:

一、代碼設置TextView的Paint屬性

首先聲明控件並初始化,然後設置屬性
//TextView加下劃線
TextView tv1 = (TextView)findViewById(R.id.text);
tv1.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下劃線
tv1.getPaint().setAntiAlias(true);//抗鋸齒
tv1.setTextColor(Color.parseColor("#ff0000"));

二、使用html用法

首先將文字寫在資源文件 strings.xml裏

<resources>
    <string name="app_name">textview</string>
    <string name="phone"><u>那就這樣吧</u></string>
</resources>

然後在佈局文件裏使用。

<TextView
    android:id="@+id/text2"
    android:layout_width="wrap_content"
    android:layout_marginTop="20dp"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_gravity="center_horizontal"
    android:text="@string/phone"
    android:textSize="20sp" />

這樣下劃線就添加成功了。最近喜歡聽那就這樣吧 這首歌.........

三、用Html類的fromHtml()方法。

這種方法和第二種類似,區別是這種方法是用代碼設置

//代碼使用Html.fromHtml()
TextView tv4 = (TextView)findViewById(R.id.text4);
tv4.setText(Html.fromHtml("<u>"+"沒有什麼能夠阻擋,我對自由的嚮往"+"</u>"));
這樣就設置成功了。

四、TextView的android:autoLink屬性

比如一段話中有URL,電話,郵件等的時候,可以設置該屬性。例如 我的郵箱是:[email protected].然後設置TextView的android:autoLink屬性,就會自動在郵箱下添加下劃線。文字下是沒有的。屬性有多種可以根據需求選擇。

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text3"
    android:layout_width="wrap_content"
    android:layout_marginTop="20dp"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_gravity="center_horizontal"
    android:autoLink="all"
    android:text="郵箱:[email protected] 電話:10000"
    android:textSize="20sp" />

五、Spannable或實現它的類,如SpannableString來格式部分字符串。

SpannableString的功能有很多,比如添加背景色,文字顏色,修飾效果,添加下劃線等等。
我是通過下面這篇博客學習的:

http://blog.csdn.net/u011102153/article/details/52485650



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章