前言
android中通过SpannableStringBuilder实现一个TextView中不同颜色显示和部分文字的点击事件
提示:以下是本篇文章正文内容,下面案例可供参考
一、ClickableSpan添加部分文字的点击事件
val mSpannableStringBuilder: SpannableStringBuilder = SpannableStringBuilder()
mSpannableStringBuilder.append("登录/注册即表示同意<<用户协议>>")
val mClickableSpan: ClickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
val action = RichTextFragmentArgs("title", "type").toBundle()
Navigation.findNavController(widget).navigate(R.id.richText, action)
}
}
mSpannableStringBuilder.setSpan(
mClickableSpan, 10, mSpannableStringBuilder.length,
Spannable.SPAN_INCLUSIVE_INCLUSIVE
)
mFragmentLoginBinding!!.tvUserAgreement.highlightColor =
Color.TRANSPARENT //设置点击后的颜色为透明,否则会一直出现高亮
mFragmentLoginBinding!!.tvUserAgreement.text = mSpannableStringBuilder
mFragmentLoginBinding!!.tvUserAgreement.movementMethod = LinkMovementMethod.getInstance()
设置字体可点击后,可点击部分字体的颜色会变。
二、ForegroundColorSpan设置部分字体的颜色
val mForegroundColorSpan: ForegroundColorSpan =
ForegroundColorSpan(requireActivity().resources.getColor(R.color.green_FF00612E))
mSpannableStringBuilder.setSpan(
mForegroundColorSpan, 10, mSpannableStringBuilder.length,
Spannable.SPAN_INCLUSIVE_INCLUSIVE
)
mFragmentLoginBinding!!.tvUserAgreement.text = mSpannableStringBuilder
三.先设置可点击,再设置字体颜色
val mSpannableStringBuilder: SpannableStringBuilder = SpannableStringBuilder()
mSpannableStringBuilder.append(mFragmentLoginBinding!!.tvUserAgreement.text.toString())
val mClickableSpan: ClickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
val action = RichTextFragmentArgs("title", "type").toBundle()
Navigation.findNavController(widget).navigate(R.id.richText, action)
}
}
mSpannableStringBuilder.setSpan(
mClickableSpan, 10, mSpannableStringBuilder.length,
Spannable.SPAN_INCLUSIVE_INCLUSIVE
)
mFragmentLoginBinding!!.tvUserAgreement.highlightColor =
Color.TRANSPARENT //设置点击后的颜色为透明,否则会一直出现高亮
mFragmentLoginBinding!!.tvUserAgreement.text = mSpannableStringBuilder
mFragmentLoginBinding!!.tvUserAgreement.movementMethod = LinkMovementMethod.getInstance()
val mForegroundColorSpan: ForegroundColorSpan =
ForegroundColorSpan(requireActivity().resources.getColor(R.color.green_FF00612E))
mSpannableStringBuilder.setSpan(
mForegroundColorSpan, 10, mSpannableStringBuilder.length,
Spannable.SPAN_INCLUSIVE_INCLUSIVE
)
mFragmentLoginBinding!!.tvUserAgreement.text = mSpannableStringBuilder
总结
https://developer.android.com/reference/android/text/SpannableStringBuilder?hl=en