美文网首页
Android (Kotlin)工具之--设置字符串中子字符串为

Android (Kotlin)工具之--设置字符串中子字符串为

作者: 想看烟花么 | 来源:发表于2021-06-24 11:36 被阅读0次

我们总是有这样的需求:同一句话,我们需要用不同的颜色标示出来,某几个文字是超链接,支持点击引导用户到其他功能页,常见的比如在使用某项功能时,用户必须要事先需要知晓的一些协议或者约定,当一个应用庞大时,这样的场景我们时常能见到,现在简单封装成了一个工具类:

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-----------------------------

我也是有底线的,感谢您的耐心阅读,欢迎支持与点赞。

相关文章

网友评论

      本文标题:Android (Kotlin)工具之--设置字符串中子字符串为

      本文链接:https://www.haomeiwen.com/subject/vlclyltx.html