多样式富文本的简洁实现
原文链接:Android UI开发之多样式富文本的简洁实现
AppendableStyleString
允许你快速构建多种样式文字。
特性
- 支持对于同一个字符串设置多种样式。
- 支持文字和图片。
- 提供默认样式。
- 采用 DSL 确保更清晰的样式作用范围
快速开始
下面的示例为你展示了如何创建一条链接文本。
AppendableStyleString
.getStyleScope(getBinding().tv) {
withStyle(AppendableStyle(url = "https://www.baidu.com/")) {
append("这是一个链接")
}
}
下面的示例为你展示了如果创建一条图片文本。
AppendableStyleString
.getStyleScope(getBinding().tv) {
withImage(ImageSpan(this@DateActivity, R.mipmap.ic_launcher))
}
拼接字符串
下面的示例为你展示如何创建一条复杂的富文本字符串。
AppendableStyleString
.getStyleScope(getBinding().tv) {
withStyle(AppendableStyle(url = "https://www.baidu.com/")) {
append("这是一个链接")
}
withStyle(AppendableStyle(strikeMode = StrikeMode.UNDERLINE)) {
append("这是一个带下划线的句子")
}
withStyle(AppendableStyle(backColor = R.color.md_theme_primary)) {
append("这是带颜色的文字")
}
withStyle(
AppendableStyle(scriptMode = ScriptMode.Superscript, foreColor = R.color.md_theme_tertiaryFixedDim)
) {
append("[1]")
}
withImage(ImageSpan(this@DateActivity, R.mipmap.ic_launcher))
}
通用样式
通过指定 AppendableStyle
内的 backColor
属性,可以为字符串设置背景色。目前 AppendableStyle
允许你指定以下属性:
- foreColor : 文字颜色。
- backColor : 文字背景色。
- fontStyle : 文字风格,目前支持粗体、斜体或者正常。
- fontFamily : 文字字体。
- fontSize : 文字大小。
- fontAlign : 文字对齐方式。
- proportion : 文字放大比例,例如如果放大 50% ,则该属性设置为 1.5f 。
- xProportion : 值 > 1.0 会将文本拉伸得更宽。值 < 1.0 会将文本拉伸得更窄。
AppendableStyleString
.getStyleScope(getBinding().tv) {
withStyle(AppendableStyle(
url = "https://www.baidu.com/", backColor = R.color.lightslategray
)) {
append("这是一个链接")
}
}
特殊样式
除了通用样式,你也可以为文字指定以下唯一的特殊样式,目前支持:
链接文字
AppendableStyleString
.getStyleScope(getBinding().tv) {
withStyle(AppendableStyle(url = "https://www.baidu.com/")) {
append("这是一个链接")
}
}
首行缩进
AppendableStyleString
.getStyleScope(getBinding().tv) {
withStyle(AppendableStyle(linesIndent = LeadingMarginSpan.Standard(100, 0))) {
append("这是一段带首行缩进的文本哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈。")
}
}
携带子弹点
AppendableStyleString
.getStyleScope(getBinding().tv) {
withStyle(
AppendableStyle(bulletSpan = BulletSpan(10, ColorUtils.colorHex2Int("#d63031"), 10))
) {
append("这是一段带子弹点的文字。")
}
}
删除线或者下划线
AppendableStyleString
.getStyleScope(getBinding().tv) {
withStyle(
AppendableStyle(strikeMode = StrikeMode.STRIKETHROUGH)
) {
append("这是一段带删除线的文字。")
}
withStyle(
AppendableStyle(strikeMode = StrikeMode.UNDERLINE)
) {
append("这是一段带下划线的文字。")
}
}
上标或者下标
AppendableStyleString
.getStyleScope(getBinding().tv) {
withStyle { append("这是一段带上标的文字。") }
withStyle(AppendableStyle(scriptMode = ScriptMode.Superscript)) {
append("[1]")
}
}
范围模糊
AppendableStyleString
.getStyleScope(getBinding().tv) {
withStyle(AppendableStyle(
blurRadius = 5f,
blur = BlurMaskFilter.Blur.NORMAL)
) {
append("这是一段带模糊的文字。")
}
}
可点击文字
该项不提供示例。
源代码
你可以点击 AppendableStyleString 来查看源码,这个仓库也包含了我封装的其他工具,如果你喜欢的话,还希望能够star,fork和提出issue。😀😀😀