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

        }
}

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

相关推荐
程序员煊子4 小时前
用 Cursor 从零搭一个 Compose 本地记账 App:实战记录与源码解析
android·kotlin·compose·cursor
alexhilton6 小时前
面向Android开发者的Google I/O 2026
android·kotlin·android jetpack
私人珍藏库6 小时前
【Android】豆图助手-永久HY-模拟微X~zfb各种截图
android·app·工具·软件·多功能
程序员陆业聪7 小时前
Shadow实战接入与生产落地:从零搭建到稳定运行
android
程序员陆业聪8 小时前
Shadow Transform:编译期的魔法——字节码替换实战
android
imuliuliang11 小时前
Laravel6.x核心特性全解析
android·php·laravel
idingzhi12 小时前
A股量化策略日报(2026年05月22日)
android·开发语言·python·kotlin
测试员周周13 小时前
【Appium 系列】第14节-断言与验证 — Validator 的设计
android·人工智能·python·功能测试·ios·单元测试·appium
赏金术士14 小时前
Android 动画对比指南:View 系统 vs Jetpack Compose
android·kotlin·compose
我命由我1234515 小时前
C++ - 面向对象 - 析构函数
android·c语言·开发语言·c++·visualstudio·visual studio·android runtime