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

        }
}

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

相关推荐
c***21292 小时前
Springboot3学习(5、Druid使用及配置)
android·学习
修炼者2 小时前
【Android 进阶】别再强转 Context 了!手把手教你优雅解耦 View 与 Activity
android·android studio
x***01062 小时前
SpringSecurity+jwt实现权限认证功能
android·前端·后端
程序员江同学3 小时前
线下活动|2025 Kotlin 中文开发者大会北京分会场
android·kotlin
李坤林4 小时前
Android Vulkan 开启VK_GOOGLE_DISPLAY_TIMING 后,一个vsync 会释放两个imageBuffer现象分析
android·vulkan
Jerry4 小时前
Compose 状态思维
android
k***45994 小时前
MySQL----case的用法
android·数据库·mysql
r***86986 小时前
Plugin ‘mysql_native_password‘ is not loaded`
android·数据库·mysql
v***59836 小时前
MySQL-mysql zip安装包配置教程
android·mysql·adb
不用89k6 小时前
Android无法区分USB摄像头是哪一个
android