Android应用开发(5)文本视图(TextView)

Android应用开发学习笔记——目录索引

本章介绍文本视图(TextView)的显示,包括:设置文本内容、设置文本大小、设置文本显示颜色。

参考Google官网:https://developer.android.com/reference/android/widget/TextView

TextView是最基础的文本显示控件,常用的基本属性和设置方法有:

XML中的属性TextView类的设置方法说明
android:textsetText设置文本内容
android:textColorsetTextColor设置文本颜色
android:textSizesetTextSize设置文本大小
android:gravitysetGravity设置文本的对齐方式

一、设置TextView显示内容

  1. Layout XML文件中设置

如:res/layout/activity_main.xml中通过属性:

android:text 设置文本

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
  1. Java 代码中设置

调用文本视图的setText()方法设置


TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Hello World!");
  1. strings.xml中设置

Android Studio不推荐在xml布局文件直接Hardcoded string

推荐在/res/values目录strings.xml文件添加,然后使用@string引用

<resources>
    <string name="app_name">TextView</string>
    <string name="textView_hello">Hello World!</string>
</resources>

res/layout/activity_main.xml

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/textView_hello"

java代码中


TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(R.string.textView_hello);

layout XML或者java代码中都从string.xml引用字符串资源,以后要显示其他内容,也只需要修改string.xml一个地方即可,Android Studio推荐使用这种方法。

二、设置TextView显示大小

  1. Layout.xml文件中设置

android:textSize设置文本大小

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"

发现输入数字中有一个下来列表:

sp:专门用来设置字体大小(和系统设置中字体大小相关,跟随系统字体一起变化)

px:像素,屏幕的最小显示单位

pt:磅,1/72英寸

mm:毫米

in:英寸,1英寸 = 2.54厘米 = 25.4毫米

dp:与设备无关的显示单位,有时也写作dip

其中常用的是px、dp和sp三种。

dp和px的转换:


int dip2px(Context context, float dp) {
    float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dp * scale + 0.5f);
}
int px2dip(Context context, int px) {
    float scale = context.getResources().getDisplayMetrics().density;
    return (int) (px / scale + 0.5f);
}
  1. Java 代码中设置

调用文本视图的setTextSize()方法设置


TextView textView = (TextView) findViewById(R.id.textView);
textView.setTextSize(30);

setTextSize()使用的是sp(COMPLEX_UNIT_SP)


    public void setTextSize(float size) {
        setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
    }

手机【设置】菜单->【显示】->【字体与显示大小】调整字体大小,可以看到使用sp文本字体大小会跟随系统变化,使用dp的不会变化。

三、设置TextView显示颜色

  1. Layout.xml文件中设置

android:textColor设置文本大小

XML 中android:textColor默认是不透明(也就是alpha = 0xFF),在前面要加“#”后面是十六进制RGB

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="@string/textView_hello"
        android:textColor="#FF0000"
  1. Java 代码中设置

调用文本视图的setTextColor()方法设置

Java代码中默认是透明(也就是alpha = 0x00),格式为ARGB,使用十六进制0x开头

如:红色0xFFFF0000、绿色0xFF00FF00、蓝色0xFF0000FF、白色0xFFFFFFFF


TextView textView = (TextView) findViewById(R.id.textView);
textView.setTextColor(0xFFFF0000);

Color类中定义了12中颜色,可以使用

Color类定义

说明

Color类定义

说明

BLACK

0xFF000000

黑色

GREEN

0xFF00FF00

绿色

DKGRAY

0xFF444444

深灰

BLUE

0xFF0000FF

蓝色

GRAY

0xFF888888

灰色

YELLOW

0xFFFFFF00

黄色

LTGRAY

0xFFCCCCCC

浅色

CYAN

0xFF00FFFF

青色

WHITE

0xFFFFFFFF

白色

MAGENTA

0xFFFF00FF

品红

RED

0xFFFF0000

红色

TRANSPARENT

0

透明


TextView textView = (TextView) findViewById(R.id.textView);
textView.setTextColor(Color.BLUE);
  1. colors.xml中设置

/res/values目录colors.xml文件添加

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
</resources>

res/layout/activity_main.xml引用@color/自定义颜色名称

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/textView_hello"
        android:textColor="@color/purple_200"

java代码中引用R.color.颜色


TextView textView = (TextView) findViewById(R.id.textView);
textView.setTextColor(R.color.purple_200);
  1. 设置背景颜色

Layout XML文件中android:background设置背景

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/textView_hello"
        android:textColor="@color/purple_200"
        android:background="#111111"

java代码中

setBackgroundColor(),参数:使用Color类或者十六进制


TextView textView = (TextView) findViewById(R.id.textView);
textView.setBackgroundColor(Color.BLUE);
// 或者
textView.setBackgroundColor(0xFF0000FF);

setBackgroundResource(), 参数:R.color.颜色,R.drawable.


TextView textView = (TextView) findViewById(R.id.textView);
textView.setBackgroundResource(R.color.black);

注意: XML属性android:background和Java方法 setBackgroundResource()用来设置控件的背景,不单背景颜色,还可以使用图片背景。图片放到/res/drawable,XML中引用方法@drawable/

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/textView_hello"
        android:background="@drawable/ic_launcher_background"

java 代码使用R.drawable.


TextView textView = (TextView) findViewById(R.id.textView);
textView.setBackgroundResource(R.drawable.ic_launcher_background);

四、TextView XML 完整属性

继承View的 XML 属性:参考https://developer.android.com/reference/android/view/View

XML 属性

android:allowUndo是否允许对可编辑文本进行撤消。 
android:autoLink控制是否自动查找 URL 和电子邮件地址等链接并将其转换为可单击链接。 
android:autoSizeMaxTextSize自动调整文本大小时要使用的最大文本大小约束。 
android:autoSizeMinTextSize自动调整文本大小时要使用的最小文本大小约束。 
android:autoSizePresetSizesautoSizeTextType与set to 结合使用的资源维度数组 uniform。 
android:autoSizeStepGranularityautoSizeTextType如果设置为 ,则指定自动调整大小的步长uniform。 
android:autoSizeTextType指定自动调整大小的类型。 
android:autoText如果设置,则指定此 TextView 具有文本输入方法并自动更正一些常见的拼写错误。 
android:breakStrategy中断策略(控制段落布局)。 
android:bufferType确定 getText() 将返回的最小类型。 
android:capitalize如果设置,则指定此 TextView 具有文本输入方法,并且应自动将用户键入的内容大写。 
android:cursorVisible使光标可见(默认)或不可见。 
android:digits如果设置,则指定此 TextView 有数字输入方法,并且这些特定字符是它将接受的字符。 
android:drawableBottom要在文本下方绘制的可绘制对象。 
android:drawableEnd要绘制到文本末尾的可绘制对象。 
android:drawableLeft要绘制到文本左侧的可绘制对象。 
android:drawablePadding可绘制对象和文本之间的填充。 
android:drawableRight要绘制在文本右侧的可绘制对象。 
android:drawableStart要绘制到文本开头的可绘制对象。 
android:drawableTint应用于复合(左、上等)绘图的色调。 
android:drawableTintMode用于应用复合(左、上等)可绘制色调的混合模式。 
android:drawableTop要在文本上方绘制的可绘制对象。 
android:editable如果设置,则指定此 TextView 有输入法。 
android:editorExtras对包含要 <input-extras> 提供给输入方法的附加数据的 XML 资源的引用,该资源对于输入方法的实现而言是私有的。 
android:elegantTextHeight优雅的文本高度,特别是对于不太紧凑的复杂脚本文本。 
android:ellipsize如果设置,则会导致长度超过视图宽度的单词被省略而不是在中间断开。 
android:ems使 TextView 正好有这么多 em 宽。 
android:enabled指定是否启用小部件。 
android:fallbackLineSpacing是否考虑显示文本时使用的后备字体的上升和下降。 
android:firstBaselineToTopHeight从 TextView 顶部到第一个文本基线的距离。 
android:focusedSearchResultHighlightColor重点搜索结果突出显示的颜色。 
android:focusedSearchResultHighlightColor重点搜索结果突出显示的颜色。 
android:fontFamily文本的字体系列(由字符串命名或作为字体资源引用)。 
android:fontFeatureSettings字体功能设置。 
android:fontVariationSettings字体变化设置。 
android:freezesText如果设置,文本视图将在其冻结的冰柱内包含当前的完整文本以及当前光标位置等元数据。 
android:gravity指定当文本小于视图时如何按视图的 x 轴和/或 y 轴对齐文本。 
android:height使 TextView 正好这么高。 
android:hint文本为空时显示的提示文本。 
android:hyphenationFrequency自动连字的频率。 
android:imeActionId提供输入法连接到文本视图时使用的  值 。EditorInfo.actionId
android:imeActionLabel提供输入法连接到文本视图时使用的  值 。EditorInfo.actionLabel
android:imeOptions您可以在与编辑器关联的 IME 中启用其他功能,以改进与应用程序的集成。 
android:includeFontPadding为上升和下降留出足够的空间,而不是严格使用字体上升和下降。 
android:inputMethod如果设置,则指定此 TextView 应使用指定的输入方法(由完全限定的类名指定)。 
android:inputType放置在文本字段中的数据类型,用于帮助输入法决定如何让用户输入文本。 
android:justificationMode论证模式。 
android:lastBaselineToBottomHeight从 TextView 底部到最后一个文本基线的距离。 
android:letterSpacing文本字母间距。 
android:lineBreakStyle指定文本换行的换行策略。 
android:lineBreakWordStyle指定文本换行的换行策略。 
android:lineHeight文本行之间的显式高度。 
android:lineSpacingExtra文本行之间的额外间距。 
android:lineSpacingMultiplier文本行之间的额外间距,作为乘数。 
android:lines使 TextView 恰好有这么多行高。 
android:linksClickable如果设置为 false,则即使自动链接导致找到链接,也不会将移动方法设置为链接移动方法。 
android:marqueeRepeatLimit重复选取框动画的次数。 
android:maxEms使 TextView 最多有这么多 em 宽。 
android:maxHeight使 TextView 最多有这么多像素高。 
android:maxLength设置输入过滤器以将文本长度限制为指定数字。 
android:maxLines使 TextView 最多有这么多行高。 
android:maxWidth使 TextView 最多有这么多像素宽。 
android:minEms使 TextView 至少有这么多 em 宽。 
android:minHeight使 TextView 至少有这么多像素高。 
android:minLines使 TextView 至少有这么多行高。 
android:minWidth使 TextView 至少有这么多像素宽。 
android:numeric如果设置,则指定此 TextView 有数字输入方法。 
android:password该字段的字符是否显示为密码点而不是其本身。 
android:phoneNumber如果设置,则指定此 TextView 有电话号码输入方法。 
android:privateImeOptions提供给附加到文本视图的输入法的附加内容类型描述,该描述对于输入法的实现是私有的。 
android:scrollHorizontally是否允许文本比视图更宽(因此可以水平滚动)。 
android:searchResultHighlightColor搜索结果突出显示的颜色。 
android:searchResultHighlightColor搜索结果突出显示的颜色。 
android:selectAllOnFocus如果文本可选,则在视图获得焦点时将其全部选中。 
android:shadowColor在文本下方放置一个模糊的文本阴影,并用指定的颜色绘制。 
android:shadowDx文本阴影的水平偏移。 
android:shadowDy文本阴影的垂直偏移。 
android:shadowRadius文本阴影的模糊半径。 
android:singleLine将文本限制为单个水平滚动行,而不是让它换行到多行,并在按 Enter 键时前进焦点而不是插入换行符。 
android:text要显示的文本。 
android:textAllCaps文本全部大写。 
android:textAppearance基本文本颜色、字体、大小和样式。 
android:textColor文字颜色。 
android:textColorHighlight文本选择突出显示的颜色。 
android:textColorHint提示文本的颜色。 
android:textColorLink链接的文本颜色。 
android:textCursorDrawable引用将在插入光标下绘制的可绘制对象。 
android:textFontWeightTextView 中使用的字体粗细。 
android:textIsSelectable表示可以选择不可编辑文本的内容。 
android:textScaleX设置文本的水平缩放因子。 
android:textSelectHandle引用一个可绘制对象,该可绘制对象将用于显示文本选择锚点,以将光标定位在文本中。 
android:textSelectHandleLeft引用将用于在选择区域左侧显示文本选择锚点的可绘制对象。 
android:textSelectHandleRight引用将用于在选择区域右侧显示文本选择锚点的可绘制对象。 
android:textSize文字的大小。 
android:textStyle文本的样式(正常、粗体、斜体、粗体|斜体)。 
android:typeface文本字体(普通、无衬线、等宽字体)。 
android:width使 TextView 正好这么宽。 

五、TextView控件测试程序

java:

MainActivity.java


package com.example.textviewtest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private final static String TAG = "lzl-test-Textview";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(R.string.textView_hello);

        TextView textView_setTextSize = (TextView) findViewById(R.id.textView_setTextSize);
        textView_setTextSize.setTextSize(20);

        TextView textView_setLayoutParams = (TextView) findViewById(R.id.textView_setLayoutParams);
        ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
        Log.i(TAG, "getLayoutParams:width:" + layoutParams.width + ", height:" + layoutParams.height);
        layoutParams.width = dp2px(this, 400);
        layoutParams.height = dp2px(this, 20);
        textView_setLayoutParams.setBackgroundColor(Color.GREEN);
        textView_setLayoutParams.setText("setLayoutParams:width:" + 400 + ", height:" + 20);
        textView_setLayoutParams.setLayoutParams(layoutParams);

        TextView textView_java_color = (TextView) findViewById(R.id.textView_java_color);
        textView_java_color.setTextColor(Color.RED);

        TextView textView_java_color1 = (TextView) findViewById(R.id.textView_java_color1);
        textView_java_color1.setTextColor(0xFFFF0000); //ARGB

        TextView textView_java_background = (TextView) findViewById(R.id.textView_java_background);
        textView_java_background.setTextColor(Color.RED);
        textView_java_background.setBackgroundColor(Color.GRAY);
        //textView_java_background.setBackgroundColor(0xFF888888);

        TextView textView_java_background1 = (TextView) findViewById(R.id.textView_java_background1);
        textView_java_background1.setTextColor(Color.RED);
        textView_java_background1.setBackgroundResource(R.color.gray);
    }

    int dp2px(Context context, float dp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    int px2dip(Context context, int px) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }
}

xml:

res/layout/activity_main.xml

<?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=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="vertical">
            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="@string/textView_hello"/>
            <TextView
                android:id="@+id/textView_px"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:textSize="20px"
                android:text="文本视图xml设置textSize:20px" />
            <TextView
                android:id="@+id/textView_dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:textSize="20dp"
                android:text="文本视图xml设置textSize:20dp"
                android:background="@color/blue"/>
            <TextView
                android:id="@+id/textView_sp"
                android:layout_width="350dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:textSize="20sp"
                android:text="文本视图xml设置textSize:20sp"
                android:background="@color/blue"/>
            <TextView
                android:id="@+id/textView_setTextSize"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="文本视图Java setTextSize:20sp"/>
            <TextView
                android:id="@+id/textView_setLayoutParams"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="setLayoutParams"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_marginTop="20dp"
            android:orientation="vertical">
            <TextView
                android:id="@+id/textView_xml"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#FF0000"
                android:text="文本视图:使用xml #FF0000指定红色"/>
            <TextView
                android:id="@+id/textView_res_color"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/red"
                android:text="文本视图:使用xml @color/red指定红色"/>
            <TextView
                android:id="@+id/textView_java_color"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="文本视图:使用java Color.RED指定红色"/>
            <TextView
                android:id="@+id/textView_java_color1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="文本视图:使用java 0xFFFF0000指定红色"/>
            <TextView
                android:id="@+id/textView_xml_background"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/red"
                android:background="@color/gray"
                android:text="文本视图:使用xml指定红色文字,灰色背景"/>
            <TextView
                android:id="@+id/textView_java_background"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="文本视图:使用java函数setBackgroundColor背景色"/>
            <TextView
                android:id="@+id/textView_java_background1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="文本视图:使用java函数setBackgroundResource背景色"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_marginTop="20dp"
            android:orientation="vertical">
            <TextView
                android:id="@+id/textView_gravity1"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:background="@color/gray"
                android:gravity="left"
                android:text="控件内部对齐方式:left"/>
            <TextView
                android:id="@+id/textView_gravity2"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginTop="5dp"
                android:background="@color/gray"
                android:gravity="right"
                android:text="控件内部对齐方式:right"/>
            <TextView
                android:id="@+id/textView_gravity3"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginTop="5dp"
                android:background="@color/gray"
                android:gravity="center"
                android:text="控件内部对齐方式:center"/>
            <TextView
                android:id="@+id/textView_gravity4"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginTop="5dp"
                android:background="@color/gray"
                android:gravity="bottom"
                android:text="控件内部对齐方式:bottom"/>
        </LinearLayout>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

res/values/colors.xml中添加

    <color name="white">#FFFFFFFF</color>
    <color name="red">#FFFF0000</color>
    <color name="green">#FF00FF00</color>
    <color name="blue">#FF0000FF</color>
    <color name="gray">#FF888888</color>

res/values/strings.xml

<resources>
    <string name="app_name">TextView Test</string>
    <string name="textView_hello">Hello World!</string>
</resources>

模拟器上运行

源码

百度网盘链接:百度网盘 请输入提取码 提取码:test

github下载地址:

GitHub - liuzhengliang1102/AndroidStudio-LearnAppDevelopment

点此查看Android应用开发学习笔记的完整目录

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liuzl_2010

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值