我们总是有这样的需求:同一句话,我们需要用不同的颜色标示出来,某几个文字是超链接,支持点击引导用户到其他功能页,常见的比如在使用某项功能时,用户必须要事先需要知晓的一些协议或者约定,当一个应用庞大时,这样的场景我们时常能见到,现在简单封装成了一个工具类:
object ClickableSpanStringUtil {
/**
* Insert [spanText] into [fullText] and create specified [SpannableStringBuilder].
*/
fun setSpannableString(textView: TextView, spanText: String, fullText: String, @ColorInt maybeThemeColor: Int?, builder: SpannableStringBuilder? = null, styleType: Int = Typeface.NORMAL, onClickCallback: ((String) -> Unit)? = null): SpannableStringBuilder {
val tempBuilder = builder ?: SpannableStringBuilder(fullText)
// get locate of span text in the full text.
val range = getTextSpanRange(spanText, fullText)
range?.let {
tempBuilder.setSpan(createClickableSpan(spanText, maybeThemeColor, onClickCallback), it.startIndex, it.endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
tempBuilder.setSpan(StyleSpan(styleType), it.startIndex, it.endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
textView.text = tempBuilder
textView.linksClickable = true
textView.movementMethod = LinkMovementMethod.getInstance()
return tempBuilder
}
/**
* Create [spanText] clickable span, and modify click event and ui.
*/
private fun createClickableSpan(spanText: String, @ColorInt color: Int?, onClick: ((String) -> Unit)?): ClickableSpan {
return object : ClickableSpan() {
override fun onClick(widget: View) {
// prevent CheckBox state from being toggled when click link is clicked.
widget.cancelPendingInputEvents()
onClick?.invoke(spanText)
}
override fun updateDrawState(ds: TextPaint) {
color?.let {
ds.color = it
ds.isUnderlineText = false
}
}
}
}
/**
* The SpanRange specify the range of a text span.
*/
private data class SpanRange(val startIndex: Int, val endIndex: Int)
/**
* Get the start and end of the [spanText] range in the [fullText].
*/
private fun getTextSpanRange(spanText: String, fullText: String): SpanRange? {
val startIndex = fullText.indexOf(spanText)
if (startIndex != -1 && startIndex < fullText.length) {
val endIndex = startIndex + spanText.length
return SpanRange(startIndex, endIndex)
}
return null
}
}
-----------------------------End-----------------------------
网友评论