1.简介
向用户显示文本的用户界面元素。
2.常见使用
2.1 设置文本内容
//xml 硬编码
<TextView android:text="文本"/>
//xml 推荐放在string.xml,为了国际化考虑
<TextView android:text="@string/app_name"/>
//kotlin
tv.text = getString(R.string.app_name)
2.2 字体大小
//xml
<TextView android:textSize = "16sp"/>
//kotlin 默认单位:TypedValue.COMPLEX_UNIT_SP
tv.textSize = 16f
注意 设置字体为SP,会随着手机系统设置改变字体大小,从而导致布局出现问题,特别是老年机上。
建议可以用 dp 代替,或者屏蔽 SP 的功能
方法:在 BaseActivity 中重写
override fun getResources(): Resources {
val res = super.getResources()
val configuration = res.configuration
if (configuration.fontScale != 1.0f) {
configuration.fontScale = 1.0f
}
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
createConfigurationContext(configuration).resources
} else {
res.updateConfiguration(configuration, res.displayMetrics)
res
}
}
2.3 字体颜色
//xml 硬编码
<TextView android:textColor= "#000000" / >
//xml 推荐 在colors.xml
<TextView android:textColor= "@color/tv_title_black" / >
//kotlin
tv.setTextColor(ContextCompat.getColor(context,R.color.black))
2.4 字体风格(加粗,斜体)
//xml 加粗
<TextView android:textStyle="bold"/ >
//xml 加粗和斜体
<TextView android:textStyle="bold|italic"/>
2.5 控制单行显示
//方法一 单行显示(方法过时了),虽然过时了,但是在某些场景下和 maxLines 有区别
<TextView android:singleLine="true"/ >
//方法二 单行显示,末尾显示...
<TextView
android:maxLines="1"
android:ellipsize="end"/ >
//ellipsize 属性
- end 在末尾省略
- start 在开始省略
- middle 在中间省略
- marquee 走马灯(不建议使用,cpu消耗比较大)
- none 不省略(默认模式)
2.6 文字显示的位置
<TextView android:gravity="center"/ >
|center|文字居中|
|center_vertical|文字垂直居中|
|center_horizontal|文字水平居中|
|left|文字左对齐|
|right|文字右对齐|
|top|文字顶部对齐|
|bottom|文字底部对齐|
|start|文字开头对齐(适配RLT)|
|end|文字结尾对齐(适配RLT)|
|clip_vertical|沿着对象的垂直轴裁剪|
|clip_horizontal|沿着对象的水平轴裁剪|
|fill|fill_vertical和fill_horizontal,拉伸充满控件|
|fill_horizontal|left和right,横向拉伸充满控件|
|fill_vertical|top和bottom,纵向拉伸充满控件|
2.7 修改字体
自定义字体会导致字体偏上?
https://fonts.google.com/
3.业务场景
3.1 富文本
使用时需要注意 Index 越界的问题
SPAN_INCLUSIVE_EXCLUSIVE [0,10)
SPAN_INCLUSIVE_INCLUSIVE [0,10]
SPAN_EXCLUSIVE_EXCLUSIVE (0,10)
SPAN_EXCLUSIVE_INCLUSIVE (0,10]
3.2 超链接文本
为一段文字中的某段文字添加点击事件,常见业务: 登录模块的隐私政策和用户协议
3.3 给文字设置点击效果
创建一个 selector 文件 select_tv_text.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="@color/colorAccent" />
<item android:state_focused="true" android:color="@color/colorAccent" />
<item android:state_pressed="true" android:color="@color/colorAccent" />
<item android:color="@color/colorPrimary"/>
</selector>
设置到 TextView
<TextView ...android:textColor="@drawable/select_tv_text"/>
3.4 自动适配文字大小
Android的TextView自动适配文本大小的几种方案 - 掘金
4.其他
4.1 AppCompatTextView 和 TextView
AppcompatTextView 是兼容低版本的 TextView。项目中的 TextView 会被 LayoutFactor 转化成 AppcompatTextView。但是自己编写的自定义View不会,建议编写继承TextView的自定义控件时,改用继承 AppcompatTextView
4.2 工程化
建议 用 Style 对字体大小,颜色等属性进行封装,方便统一修改