Android开发学习笔记——5、设置文本属性
2026/7/24 19:47:38 网站建设 项目流程

一、Android 设置文本内容两种方式

方式1:XML布局静态设置(写死文字)

在布局文件TextView标签直接写android:text

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="静态文字"/>

一般在开发过程中,不使用硬编码,一般会把文字或者颜色这类的属性放到strings.xml中,这不仅是一种开发规范,同时也方便后续维护以及拓展多语言。

如这里的 android:text="静态文字",可以放到strings.xml中,放进去之后这里的android:text="静态文字"就可以变成android:text="@string/text_static"

<resources> <!-- 定义文本,name为标识名,值为要展示的文字 --> <string name="text_static">静态文字</string> <string name="btn_jump">跳转到第二个页面</string> <string name="page_two_tip">这是第二个页面</string> </resources>

方式2:Java代码动态设置(运行时修改)

  1. 给TextView设置id
<TextView android:id="@+id/tv_text" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
  1. Activity中通过setText()赋值
// 找到控件 TextView tv = findViewById(R.id.tv_text); // 动态设置文字 tv.setText("代码动态文字");

补充区分

  1. XML:固定文字,页面加载就显示,不能动态变化
  2. 代码setText:程序运行后随时修改文字(接口返回、点击切换文字都用这个)

二、Android 设置文字大小两种方式

方式1:XML布局静态设置

使用android:textSize属性,单位推荐sp(适配字体缩放)

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp"/>

规范写法(放入dimens.xml资源,不硬编码):

<!-- res/values/dimens.xml --> <dimen name="text_normal">18sp</dimen> <!-- 布局引用 --> <TextView android:textSize="@dimen/text_normal"/>

方式2:Java代码动态设置

setTextSize()方法,默认单位是 sp

TextView tv = findViewById(R.id.tv_text); // 直接设置大小 tv.setTextSize(18); // 读取dimens资源写法(规范) float size = getResources().getDimension(R.dimen.text_normal); tv.setTextSize(size);

补充要点

  1. sp:专门用于文字,会跟随系统字体大小变化;
  2. dp:仅用于控件宽高,不建议给文字使用;
  3. 统一尺寸放入dimens.xml,方便全局统一修改、维护。

三、Android 设置文本颜色两种方式

方式1:XML布局静态设置

1.1 硬编码写法

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FF0000"/>

1.2 规范资源写法

先在res/values/colors.xml定义颜色

<resources> <color name="red">#FF0000</color> </resources>

布局引用

<TextView android:textColor="@color/red"/>

方式2:Java代码动态设置

2.1 读取资源颜色(规范推荐)

TextView tv = findViewById(R.id.tv_text); tv.setTextColor(getResources().getColor(R.color.red));

2.2 直接写色值(硬编码,不推荐)

tv.setTextColor(0xFFFF0000);

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询