You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TextInputLayout设为禁用时将TextInputEditText内文本设置为灰色

问题原因

TextInputLayout的禁用状态只会修改自身背景、边框、hint等关联样式,不会覆盖子级TextInputEditText的默认文本颜色配置,因此会出现容器变灰但文字仍为黑色的不一致表现。

实现方案

方案1:XML配置ColorStateList(推荐)

该方案无需额外写逻辑代码,状态切换自动生效:

  • 在res/color目录下新建颜色选择器文件et_text_color_selector.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 禁用状态文本颜色,可和官方控件禁用灰色保持一致 -->
    <item android:state_enabled="false" android:color="@color/mtrl_on_surface_disabled" />
    <!-- 正常状态文本颜色 -->
    <item android:color="@color/design_default_color_on_background" />
</selector>
  • 给TextInputEditText的android:textColor属性绑定上述选择器:
<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/InputTextContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/et_text_color_selector" />

</com.google.android.material.textfield.TextInputLayout>

配置完成后,只要修改TextInputLayout的isEnabled属性,内部EditText的文字颜色会自动跟随状态切换。

方案2:代码动态同步修改

如果需要灵活控制颜色规则,可在修改TextInputLayout状态时同步修改EditText文本颜色:

  • Kotlin示例:
// 禁用控件
InputTextContainer.isEnabled = false
InputTextContainer.editText?.setTextColor(
    ContextCompat.getColor(this, R.color.mtrl_on_surface_disabled)
)

// 启用控件
InputTextContainer.isEnabled = true
InputTextContainer.editText?.setTextColor(
    ContextCompat.getColor(this, R.color.design_default_color_on_background)
)

内容的提问来源于stack exchange,提问作者SoulReaver313

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:57:03