Android TextView总结
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, TextView!" />
样式控制
颜色
android:textColor="#FF0000"
android:textColor="@color/red"
textView.setTextColor(Color.parseColor("#FF0000"))
textView.setTextColor(ContextCompat.getColor(context, R.color.red))
字体大小
android:textSize="16sp"
textView.setTextSize(16F)
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16F) // 等价于如上
字体样式
android:textStyle="bold" // 字体样式
android:typeface="monospace" // 字体类型
textView.setTypeface(null, Typeface.BOLD)
textView.setTypeface(Typeface.MONOSPACE)
行间距
android:lineSpacingExtra="4dp" // 额外行距
android:lineSpacingMultiplier="2" // 行距倍数
textView.setLineSpacing(4F, 2F)
最大行数&省略号
android:maxLines="2" // 最多显示几行
android:ellipsize="end" // 超过部分显示...
textView.setMaxLines(2)
textView.setEllipsize(TextUtils.TruncateAt.END)
android:singleLine="true"
等价于如下:
android:maxLines="1"
android:ellipsize="end"
富文本
变色
// 从第0个到第4个变色
val spannable = SpannableString("helloTextView!")
spannable.setSpan(ForegroundColorSpan(Color.RED), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
textView.setText(spannable)
加粗
// 从第0个到第4个加粗
spannable.setSpan(StyleSpan(Typeface.BOLD), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
点击事件
spannable.setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
Toast.makeText(context, "hello", Toast.LENGTH_SHORT).show()
}
}, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
HTML格式化
textView.setText(Html.fromHtml("<b>Bold</b> <i>Italic</i> <font color='red'>Red</font>"))
其他样式
文字阴影
android:shadowColor="#FF000000"
android:shadowDx="10"
android:shadowDy="10"
android:shadowRadius="10"
跑马灯
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="-1"
textView.isSelected = true // 必须调用
自动调整大小
必须设置宽高。
android:autoSizeTextType="uniform" // 开启自适应
android:autoSizeMaxTextSize="28sp" // 最大尺寸
android:autoSizeMinTextSize="12sp" // 最小尺寸
android:autoSizeStepGranularity="1sp" // 每步尺寸
空格
普通空格:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello world" />
不换行空格:
可以替代普通空格。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello\u00A0\u00A0world" />
全角空格:
每个空格为一个汉字宽度。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello\u3000\u3000world" />