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

        }
}

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

相关推荐
apihz33 分钟前
台风实时与历史详情查询免费 API 接口完整教程
android·开发语言·tcp/ip·dubbo·台风·天气预报
浪客川1 小时前
AOSP源码隐藏状态栏
android·aosp
没有了遇见2 小时前
AI Agent 是什么?—— 一文理解 LLM、Memory、Skills、Tools、MCP、Workflow,Context
android·前端·程序员
御坂嘀喵2 小时前
Speed Tools:一套低侵入的 Android 插件化 + 动态换肤 + 字体切换框架
android·gitee
浮江雾3 小时前
Flutter第三节----Dart中的数据类型
android·开发语言·学习·flutter·入门·函数
风和先行3 小时前
Android 数据库相关学习总结
android·数据库·学习
杉氧3 小时前
Compose 渲染内核 (3):Slot Table 与 Gap Buffer —— 极速重组的数学艺术
android·架构·android jetpack
阿巴斯甜4 小时前
ContentObserver的使用:
android
casual_clover4 小时前
【Android 控件】使用 Navigation 实现底部导航功能时左右滑动退出页面功能
android·底部导航滑动退出
urkay-4 小时前
Kotlin Flow分类
android·开发语言·kotlin