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

        }
}

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

相关推荐
huwuhang7 小时前
Winkawaks街机游戏模拟器整合ROM版 1.65 汉化修正完整版 2026.03.30
android·游戏·游戏机
yitian_hm7 小时前
MySQL主从复制与读写分离实战指南
android·mysql·adb
NEGl DRYN7 小时前
Plugin ‘mysql_native_password‘ is not loaded`
android·数据库·mysql
Derrick__18 小时前
Android混淆和加密技术
android·jvm·python
sunwenjian8869 小时前
MySQL加减间隔时间函数DATE_ADD和DATE_SUB的详解
android·数据库·mysql
ictI CABL9 小时前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
放学以后Nicetry11 小时前
Android SELinux 指南:从基本概念到实战修复
android
CCIE-Yasuo11 小时前
《永恒战士2-无双战神》无限金币版(提供apk下载)安卓Android逆向记录学习-Deepseek-AI辅助
android·java·学习·游戏
jzlhll12312 小时前
kotlin flow去重distinctUntilChanged vs distinctUntilChangedBy
android·开发语言·kotlin
渡我白衣13 小时前
【MySQL基础】(3):MySQL库与表的操作
android·数据库·人工智能·深度学习·神经网络·mysql·adb