Android 自定义Edittext 和TextView 提示文字和填入内容不同的粗细组件

近期项目中又EditText 以及TextView 这两个组件需要用到提示文字 以及 填入文字要保持不同的粗细程度,所以记录一下

首先 是EditText 组件的自定义

BLEditText 继承的这个组件是一个三方的组件,可以在很大程度上减少drawable的编写,有兴趣的可以去相关的Git去看一下 点击查看,也可以直接继承Edittext,使用的时候直接调用即可

java 复制代码
class AutoBoldEditText : BLEditText {
    constructor(context: Context?) : super(context) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defstyleAttr: Int) : super(
        context,
        attrs,
        defstyleAttr
    ) {
        init()
    }

    private fun init() {
        //动态设置内容的粗细
        addTextChangedListener {
            typeface = if (it.toString().isEmpty()) {
                Typeface.DEFAULT
            } else {
                Typeface.DEFAULT_BOLD
            }
        }
    }
}

下面是TextView的组件

同理,继承也可以直接继承TextView

java 复制代码
class AutoBoldTextView(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) :
    BLTextView(context, attrs, defStyleAttr) {
        init {
            addTextChangedListener {
                if (it.toString().isEmpty()){
                    typeface = Typeface.DEFAULT
                }else {
                    typeface = Typeface.DEFAULT_BOLD
                }
            }

        }
}

做个记录,有帮助的话,点个赞意思一下呗

相关推荐
colicode16 小时前
安卓Android语音验证码接口API示例代码:Kotlin/Java版App验证开发
android·java·前端·前端框架·kotlin·语音识别
程序员敲代码吗16 小时前
解析Kotlin中元组的多返回值实现
android·开发语言·kotlin
冬奇Lab1 天前
应用异常退出实战分析:一次"幽灵杀手"引发的车载系统故障排查
android·性能优化·debug
Ehtan_Zheng1 天前
如何简化状态和实体映射Kotlin接口,委托和协变泛型
android
飘逸飘逸1 天前
Autojs进阶前言
android·javascript
spencer_tseng1 天前
Branding Printing System (Android Pad)
android·pad
FrameNotWork1 天前
多设备 Android Logcat 自动采集方案:基于 Docker + Shell 实现日志按天切割与自动清理
android·docker·容器
bqliang1 天前
Compose 实验性 Styles API
android·android jetpack
大尚来也1 天前
PHP 入门指南:从零基础到掌握核心语法
android