在日常开发中,我们经常需要使用到TextView Span的各种常用样式,但Android提供的设置API也并不友好,无法快速使用,所以我做了一个开源Library项目,方便大家集成后,一行代码简单实现Android TextView常用样式Span。
1.集成方式:
allprojects {
repositories {
...
maven { url 'https://www.jitpack.io' }
}
}
implementation 'com.github.Arcns.arc-fast:span:1.23.1'
2.使用方式
val spannableStringBuilder = SpannableStringBuilder()
// 添加图片的宽高、间距、点击事件等常用样式使用appendFastImageStyle
spannableStringBuilder.appendFastImageStyle(
context = requireContext(),
drawableRes = R.mipmap.ic_launcher_round
) {
width = 20.dp //图片宽度
height = 20.dp //图片高度
padding = 8.dp //图片间距
onClick = {
// 点击图片回调
}
}
// 添加带圆角边框的文字使用appendFastSpan与FastTextWrapSpan
spannableStringBuilder.appendFastSpan(
"满99元减10元",
FastTextWrapSpan(
radius = 4f.dp, // 边框的圆角
borderSize = 1f.dp, // 边框的大小
borderColor = R.color.main.color,// 边框的颜色
textSize = 12f.sp, // 文字的大小
textColor = R.color.main.color, // 文字的颜色
textRightMargin = 6f.dp, // 文字的右外边距
topPadding = 2f.dp, // 文字的上内边距
bottomPadding = 2f.dp,// 文字的下内边距
leftPadding = 6f.dp,// 文字的左内边距
rightPadding = 6f.dp// 文字的右内边距
)
)
spannableStringBuilder.append(
"华为平板MatePad 11 平板电脑120Hz高刷全面屏 鸿蒙HarmonyOS 6G+128GB WIFI 曜石灰 WIFI海岛蓝"
)
// 添加文字之间的间距使用appendFastSpacing
spannableStringBuilder.appendFastSpacing(6.dp)
// 添加文字的颜色、大小、加粗、点击事件等常用样式使用appendFastTextStyle
spannableStringBuilder.appendFastTextStyle("10月31日-11月3日的订单,预计在2日内发货") {
textColor = 0xFF999999.toInt() // 文字颜色
textSize = 14.sp // 文字大小
textStyle = Typeface.BOLD // 文字加粗
onClick = {
// 点击文字回调
}
}
binding.tvTitle.text = spannableStringBuilder
binding.tvTitle.enableClickableSpan() // 启用点击事件