Android:TextView控制元件

yufan發表於2016-01-08

3.2.1    TextView

 

TextView 可以說是 Android 中最簡單的一個控制元件了,你在前面其實也已經和它打過了一 些打交道。它主要用於在介面上顯示一段文字資訊,比如你在第一章看到的 Hello world!下 面我們就來看一看關於 TextView 的更多用法。

將 activity_main.xml 中的程式碼改成如下所示:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >

 

<TextView android:id="@+id/text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="This is TextView" />

 

</LinearLayout>

外面的 LinearLayout 先忽略不看,在 TextView 中我們使用 android:id 給當前控制元件定義了 一個唯一識別符號,這個屬性在上一章中已經講解過了。然後使用 android:layout_width 指定了 控制元件的寬度,使用 android:layout_height 指定了控制元件的高度。Android 中所有的控制元件都具有這 兩個屬性,可選值有三種 match_parent 、fill_parent 和 wrap_content,其中 match_parent 和 fill_parent 的意義相同,現在官方更加推薦使用 match_parent。match_parent 表示讓當前控制元件的大小和父佈局的大小一樣,也就是由父佈局來決定當前控制元件的大小。wrap_content 表示讓當前控制元件的大小能夠剛好包含住裡面的內容,也就是由控制元件內容決定當前控制元件的大小。所以 上面的程式碼就表示讓 TextView 的寬度和父佈局一樣寬,也就是手機螢幕的寬度,讓 TextView 的高度足夠包含住裡面的內容就行。當然除了使用上述值,你也可以對控制元件的寬和高指定一 個固定的大小,但是這樣做有時會在不同手機螢幕的適配方面出現問題。接下來我們通過 android:text 指定了 TextView 中顯示的文字內容,現在執行程式,效果如圖 3.1 所示。

 

 

 

圖   3.1

 

雖然指定的文字內容是正常顯示了,不過我們好像沒看出來 TextView 的寬度是和螢幕 一樣寬的。其實這是由於 TextView 中的文字預設是居左上角對齊的,雖然 TextView 的寬度 充滿了整個螢幕,可是從效果上完全看不出來。現在我們修改 TextView 的文字對齊方式, 如下所示:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"

android:orientation="vertical" >

 

<TextView android:id="@+id/text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="This is TextView" />

 

</LinearLayout>

我們使用 android:gravity 來指定文字的對齊方式,可選值有 top、bottom、left、right、center 等 , 可 以 用 “ | ” 來 同 時 指 定 多 個 值 , 這 裡 我 們 指 定 的 "center" , 效 果 等 同 於 "center_vertical|center_horizontal",表示文字在垂直和水平方向都居中對齊。現在重新執行程 序,效果如圖 3.2 所示。

 

 

 

圖   3.2

 

這也說明了,TextView 的寬度確實是和螢幕寬度一樣的。 另外我們還可以對 TextView 中文字的大小和顏色進行修改,如下所示:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >

 

 

<TextView android:id="@+id/text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textSize="24sp" android:textColor="#00ff00" android:text="This is TextView" />

 

</LinearLayout>

通過 android:textSize 屬性可以指定文字的大小,通過 android:textColor 屬性可以指定文 字的顏色。重新執行程式,效果如圖 3.3 所示。

 

 

 

圖   3.3

 

當然 TextView 中還有很多其他的屬性,這裡我就不再一一介紹了,需要用到的時候去 查閱文件就可以了。

相關文章