Android UI篇之TextView(五)

52 阅读1分钟

TextView

使用

1. layout
<TextView
    android:id="@+id/tv_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal|bottom"
    android:layout_marginBottom="16dp"
    android:background="@drawable/shape_80000000_radius42"
    android:drawableStart="@drawable/svg_xxx"
    android:drawablePadding="@dimen/dp_8"
    android:gravity="center"
    android:text="title"
    android:textColor="#434343"
    android:textSize="32sp" />

2. background
# shape_80000000_radius42.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#80000000"/>

    <corners android:radius="42dp"/>
</shape>

详解

TextView是Android中用于显示固定文本内容的控件,例标题、描述等

属性

  • android:maxLines="3":最大行数
  • android:ellipsize="end":结束显示...
  • android:maxLength="100":最大字符个数
  • android:singleLine="true":单行
  • android:textStyle="bold":文本样式,取值(bold、italic、normal)
  • android:textFontWeight="100":字体粗细,整数值
  • android:fontFamily="sans-serif":字体设置
  • android:letterSpacing="1.2":字母间距,浮点值
  • android:lineSpacingExtra="10.5sp":行间距,不作用于最后一行,可用单位(sp、dp、px、in、mm)
  • android:lineHeight="56dp":行高,设置后lineSpacingExtra失效
  • android:breakStrategy="high_quality":用于换行策略,取值(balanced(断线策略平衡线长度)、high_quality(换行高质量策略,例使用连字符)、simple(换行使用简单策略))
  • android:drawableStart:文本起始位置增加图标
  • android:drawablePadding:图标与文本间距设置

结合Span类实现富文本效果

  • 关键字标注颜色
fun setTextSpan(tv: TextView, text: String, keyword: String) {
    try {
        val spannable = SpannableString(text)
        val textEnd = text.indexOf(keyword)
        spannable.setSpan(
            ForegroundColorSpan(Color.BLACK), 0, textEnd - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannable.setSpan(
            ForegroundColorSpan(Color.BLUE), textEnd, text.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        tv.text = spannable
    } catch (e: Exception){
        LogTool.e("span error: ${e.message}")
    }
}