【Android】TextView前增加红色必填项星号*

自定义属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="NecessaryTextView">
        <attr name="necessary" format="boolean" />
    </declare-styleable>
</resources>
自定义控件
import android.content.Context
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

// TextView that start with a red char of *
class NecessaryTextView : AppCompatTextView {

    private var necessary = false

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.NecessaryTextView)
        necessary = typedArray.getBoolean(R.styleable.NecessaryTextView_necessary, false)
        typedArray.recycle()
        setText(text, null)
    }

    override fun setText(text: CharSequence?, type: BufferType?) {
        if (necessary) {
            val span = SpannableString("*$text")
            span.setSpan(ForegroundColorSpan(Color.RED), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            super.setText(span, type)
        } else {
            super.setText(text, type)
        }
    }
}

相关推荐

  1. 【Android】TextView增加红色星号*

    2024-03-16 22:54:03       23 阅读
  2. vue设置

    2024-03-16 22:54:03       16 阅读
  3. vue2 elementui动态

    2024-03-16 22:54:03       20 阅读
  4. php 手机

    2024-03-16 22:54:03       11 阅读
  5. php 姓名加

    2024-03-16 22:54:03       12 阅读
  6. 面试看,仅供参考

    2024-03-16 22:54:03       15 阅读
  7. 从字符串中移除

    2024-03-16 22:54:03       40 阅读

最近更新

  1. 前端导出pdf

    2024-03-16 22:54:03       0 阅读
  2. Knife4j的原理及应用详解(五)

    2024-03-16 22:54:03       0 阅读
  3. Day2--每日一练

    2024-03-16 22:54:03       0 阅读
  4. 东方博宜1626 - 暑假的旅游计划

    2024-03-16 22:54:03       0 阅读
  5. react小白面试不得不会的20个问题——第二篇

    2024-03-16 22:54:03       0 阅读
  6. 简单滤波算法伪码

    2024-03-16 22:54:03       0 阅读
  7. Mongodb索引简介

    2024-03-16 22:54:03       0 阅读
  8. Linux 6种日志查看方法

    2024-03-16 22:54:03       0 阅读
  9. 案例研究(Case Study)是什么?怎么写?

    2024-03-16 22:54:03       0 阅读
  10. Linux虚拟化技术:从Xen到KVM

    2024-03-16 22:54:03       0 阅读

热门阅读

  1. Vue3.0+vite vite.config.ts配置与env

    2024-03-16 22:54:03       19 阅读
  2. 【嵌入式——QT】线程同步

    2024-03-16 22:54:03       21 阅读
  3. Qt是什么?

    2024-03-16 22:54:03       20 阅读
  4. 第1章第2节:SAS语言基础

    2024-03-16 22:54:03       23 阅读
  5. 3月16日ACwing每日一题

    2024-03-16 22:54:03       21 阅读
  6. View UI清除表单

    2024-03-16 22:54:03       22 阅读
  7. 构建专业聊天软件:C#编程深度解析

    2024-03-16 22:54:03       22 阅读
  8. 树莓派开机自动播放U盘里的照片和视频

    2024-03-16 22:54:03       28 阅读
  9. pre_min[0:10, 2:3] = pre和pre_min[0:10, 2] = pre区别

    2024-03-16 22:54:03       22 阅读
  10. H5/微信 Video标签移动端播放问题

    2024-03-16 22:54:03       40 阅读
  11. int与integer的区别

    2024-03-16 22:54:03       19 阅读