实现效果:
亦或者是在弹窗中显示,都是一样的。
代码比较简单,涉及到SpannableStringBuilder
知识点
用到两个Span:
- ClickableSpan 处理点击事件
- ForegroundColorSpan 设置修饰
代码:
private fun setText() { //拼接字符串 val spanBuilder = SpannableStringBuilder("同意") /** * 服务协议 */ var span = SpannableString("服务协议") //服务协议点击事件 span.setSpan(object : ClickableSpan() { override fun onClick(widget: View) { Toast.makeText(this@LoginActivity,"服务协议",Toast.LENGTH_SHORT).show() } }, 0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) //设置颜色、下划线 span.setSpan( ForegroundColorSpan(Color.parseColor("#D1894A")), 0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) spanBuilder.append(span) spanBuilder.append("与") /** * 隐私政策 */ span = SpannableString("隐私政策") span.setSpan(object : ClickableSpan() { override fun onClick(widget: View) { Toast.makeText(this@LoginActivity,"隐私政策",Toast.LENGTH_SHORT).show() } }, 0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) span.setSpan( ForegroundColorSpan(Color.parseColor("#D1894A")), 0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) spanBuilder.append(span) // 赋值给TextView tv_service_agreement.movementMethod = LinkMovementMethod.getInstance() tv_service_agreement.text = spanBuilder //设置高亮颜色透明,因为点击会变色 tv_service_agreement.highlightColor = ContextCompat.getColor(applicationContext, R.color.transparent) }