TextView 是 Android 中用于显示文本内容的视图组件,它是用户界面中常用的一个基本控件。TextView 提供了丰富的属性和方法,使得文本显示更加灵活和定制化。以下是一些 TextView 的常用属性和一些详细解释:

常用属性:

1. android:text: 用于设置 TextView 中显示的文本内容。
    <TextView
        android:id="@+id/myTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, TextView!" />

2. android:textSize: 用于设置文本的字体大小。
    <TextView
        android:id="@+id/myTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, TextView!"
        android:textSize="18sp" />

3. android:textColor: 用于设置文本的颜色。
    <TextView
        android:id="@+id/myTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, TextView!"
        android:textColor="#0000FF" />

4. android:gravity: 用于设置文本在 TextView 中的对齐方式(如居中、左对齐、右对齐等)。
    <TextView
        android:id="@+id/myTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello, TextView!"
        android:gravity="center" />

5. android:fontFamily: 用于设置字体族(字体类型)。
    <TextView
        android:id="@+id/myTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, TextView!"
        android:fontFamily="sans-serif-light" />

6. android:layout_gravity: 用于设置 TextView 在其父布局中的对齐方式。
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/myTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, TextView!"
            android:layout_gravity="center" />

    </LinearLayout>

使用代码动态设置文本:

除了在 XML 中设置文本,你还可以在代码中动态设置 TextView 的文本内容:
TextView myTextView = findViewById(R.id.myTextView);
myTextView.setText("Dynamic Text");

富文本(SpannableString):

TextView 支持富文本,你可以使用 SpannableString 来设置不同部分的文本样式,如颜色、字体大小等。
TextView myTextView = findViewById(R.id.myTextView);

SpannableString spannableString = new SpannableString("Hello, TextView!");
spannableString.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new StyleSpan(Typeface.BOLD), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

myTextView.setText(spannableString);

以上只是 TextView 的一些基本属性和使用方法,你可以根据实际需求在不同的情境下进行定制。TextView 提供了丰富的功能,包括支持 HTML、链接、文本选择等,可以满足各种文本显示需求。


转载请注明出处:http://www.pingtaimeng.com/article/detail/15129/Android