Android中Textview的属性及示例

常用属性

以下是一些常用的Android TextView属性及其示例:

android:text: 设置TextView中显示的文本内容。

1
2
3
4
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!" />

android:textColor: 设置文本颜色。

1
2
3
4
5
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textColor="#FF0000" />

android:textSize: 设置文本大小。

1
2
3
4
5
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="20sp" />

android:gravity: 设置文本的对齐方式。

1
2
3
4
5
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:gravity="center" />

android:background: 设置TextView的背景颜色或背景图片。

1
2
3
4
5
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:background="#CCCCCC" />

android:padding: 设置TextView的内边距。

1
2
3
4
5
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:padding="10dp" />

android:visibility: 控制TextView的可见性。

1
2
3
4
5
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:visibility="invisible" />

android:fontFamily: 设置文本字体。

1
2
3
4
5
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:fontFamily="sans-serif" />

android:maxLines: 设置最大显示行数。

1
2
3
4
5
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a long text that will be truncated if exceeds the maximum lines set."
android:maxLines="2" />

android:ellipsize: 设置文本过长时的省略方式。

1
2
3
4
5
6
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a long text that will be truncated if exceeds the maximum lines set."
android:maxLines="1"
android:ellipsize="end" />