Android开发学习笔记——5、设置文本属性

发布时间:2026/7/24 19:47:45

Android开发学习笔记——5、设置文本属性 一、Android 设置文本内容两种方式方式1XML布局静态设置写死文字在布局文件TextView标签直接写android:textTextView android:layout_widthwrap_content android:layout_heightwrap_content android:text静态文字/一般在开发过程中不使用硬编码一般会把文字或者颜色这类的属性放到strings.xml中这不仅是一种开发规范同时也方便后续维护以及拓展多语言。如这里的 android:text静态文字可以放到strings.xml中放进去之后这里的android:text静态文字就可以变成android:textstring/text_staticresources !-- 定义文本name为标识名值为要展示的文字 -- string nametext_static静态文字/string string namebtn_jump跳转到第二个页面/string string namepage_two_tip这是第二个页面/string /resources方式2Java代码动态设置运行时修改给TextView设置idTextView android:idid/tv_text android:layout_widthwrap_content android:layout_heightwrap_content/Activity中通过setText()赋值// 找到控件 TextView tv findViewById(R.id.tv_text); // 动态设置文字 tv.setText(代码动态文字);补充区分XML固定文字页面加载就显示不能动态变化代码setText程序运行后随时修改文字接口返回、点击切换文字都用这个二、Android 设置文字大小两种方式方式1XML布局静态设置使用android:textSize属性单位推荐sp适配字体缩放TextView android:layout_widthwrap_content android:layout_heightwrap_content android:textSize18sp/规范写法放入dimens.xml资源不硬编码!-- res/values/dimens.xml -- dimen nametext_normal18sp/dimen !-- 布局引用 -- TextView android:textSizedimen/text_normal/方式2Java代码动态设置setTextSize()方法默认单位是 spTextView tv findViewById(R.id.tv_text); // 直接设置大小 tv.setTextSize(18); // 读取dimens资源写法规范 float size getResources().getDimension(R.dimen.text_normal); tv.setTextSize(size);补充要点sp专门用于文字会跟随系统字体大小变化dp仅用于控件宽高不建议给文字使用统一尺寸放入dimens.xml方便全局统一修改、维护。三、Android 设置文本颜色两种方式方式1XML布局静态设置1.1 硬编码写法TextView android:layout_widthwrap_content android:layout_heightwrap_content android:textColor#FF0000/1.2 规范资源写法先在res/values/colors.xml定义颜色resources color namered#FF0000/color /resources布局引用TextView android:textColorcolor/red/方式2Java代码动态设置2.1 读取资源颜色规范推荐TextView tv findViewById(R.id.tv_text); tv.setTextColor(getResources().getColor(R.color.red));2.2 直接写色值硬编码不推荐tv.setTextColor(0xFFFF0000);

相关新闻