Android開發(fā)學(xué)習(xí)教程(5)- 基本控件TextView用法和屬性
TextView是什么
TextView文本標(biāo)簽,常用來(lái)顯示文字的一個(gè)控件,比如第二篇章的Hello World和上一篇章中的Hello Activity。
TextView有什么用
常用來(lái)顯示文字。
TextView的使用
以上一篇章中的Hello Activity為例,我們來(lái)看看TextView的用法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?
xml
?version
=
"1.0"
?encoding
=
"utf-8"
?>
<
androidx.constraintlayout.widget.ConstraintLayout
?xmlns:android
=
"http://schemas.android.com/apk/res/android"
????
xmlns:app
=
"http://schemas.android.com/apk/res-auto"
????
xmlns:tools
=
"http://schemas.android.com/tools"
????
android:layout_width
=
"match_parent"
????
android:layout_height
=
"match_parent"
????
tools:context
=
".TestActivity"
>
????
<
TextView
????
android:layout_width
=
"wrap_content"
????
android:layout_height
=
"wrap_content"
????
android:text
=
"Hello Activity"
????
app:layout_constraintBottom_toBottomOf
=
"parent"
????
app:layout_constraintLeft_toLeftOf
=
"parent"
????
app:layout_constraintRight_toRightOf
=
"parent"
????
app:layout_constraintTop_toTopOf
=
"parent"
?/>
</
androidx.constraintlayout.widget.ConstraintLayout
>
上一篇章中我們沒(méi)有細(xì)講TextView的屬性,現(xiàn)在我們?cè)敿?xì)來(lái)看。
1
2
3
4
5
6
7
8
android:id:控件的唯一標(biāo)識(shí)ID;
android:text:要顯示的文字內(nèi)容;
android:layout_width:TextView的寬度(或者說(shuō)長(zhǎng)度),值為wrap_content意思是自適應(yīng)寬度,就是文字有多長(zhǎng),TextView的寬度就有多長(zhǎng);
android:layout_width:TextView的高度,值為wrap_content意思是自適應(yīng)高度,就是文字有多高,TextView的高度就有多高;
app:layout_constraintBottom_toBottomOf=
"parent"
:表示TextView的底部與父類控件(也就是ConstraintLayout)的底部對(duì)齊;
app:layout_constraintEnd_toEndOf=
"parent"
:表示TextView的右邊與父類控件(也就是ConstraintLayout)的右邊對(duì)齊;
app:layout_constraintStart_toStartOf=
"parent"
:表示TextView的左邊與父類控件(也就是ConstraintLayout)的左邊對(duì)齊;
app:layout_constraintTop_toTopOf=
"parent"
:表示TextView的頂部與父類控件(也就是ConstraintLayout)的頂部對(duì)齊;
以上這三個(gè)與父類對(duì)齊的屬性讀起來(lái)挺繞口的,但是在Android Studio的UI編輯器中看起來(lái)就一目了然其實(shí)就是屏幕居中了,如下:(這里如果實(shí)在不明白也沒(méi)關(guān)系,我們后面章節(jié)會(huì)著重講常用布局)
繼續(xù)看TextView常用屬性
1
2
3
4
android:textColor=
"#FF0000"
?文字的顏色為紅色
android:textSize=
"20sp"
?文字的大小為20sp
android:background=
"#cccccc"
?TextView的背景顏色為灰色
android:singleLine=
"true"
?TextView的內(nèi)容只顯示一行,超出部分顯示省略號(hào)…
我們來(lái)試試上面的屬性
1
2
3
4
5
6
7
8
9
10
11
12
<
TextView
????
android:layout_width
=
"wrap_content"
????
android:layout_height
=
"wrap_content"
????
android:text
=
"Hello Activity Hello Activity Hello Activity Hello Activity"
????
android:textColor
=
"#FF0000"
????
android:textSize
=
"20sp"
????
android:background
=
"#cccccc"
????
android:singleLine
=
"true"
????
app:layout_constraintBottom_toBottomOf
=
"parent"
????
app:layout_constraintEnd_toEndOf
=
"parent"
????
app:layout_constraintStart_toStartOf
=
"parent"
????
app:layout_constraintTop_toTopOf
=
"parent"
/>
源碼鏈接:https://yunjunet.cn/876717.html
標(biāo)簽: