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

如何修改TextInputEditText不同焦点状态下的默认下划线颜色

解决方法

你需要使用带状态的ColorStateList资源来定义不同状态下的下划线颜色,单独设置固定色值只会作用于聚焦状态。

步骤1:创建颜色状态选择器

在res/color目录下新建text_input_box_stroke.xml文件(如果没有color目录先手动新建),内容如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 聚焦状态:白色 -->
    <item android:color="@color/white" android:state_focused="true" />
    <!-- 失焦/默认状态:蓝色 -->
    <item android:color="@color/blue" />
    <!-- 可选:如果需要适配禁用状态可以添加 <item android:color="@color/gray" android:state_enabled="false"/> -->
</selector>

步骤2:修改布局配置

对原有XML做两处核心修改:

  • 给TextInputLayout设置app:boxStrokeColor为上面创建的选择器
  • 删掉TextInputEditText里的android:background="@color/primaryColor"配置,自定义background会覆盖Material组件的默认样式,导致下划线不生效

修改后的完整布局代码:

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/usernameInputLayout"
    android:layout_width="384dp"
    android:layout_height="75dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="200dp"
    android:layout_marginEnd="16dp"
    android:hint="@string/username_hint"
    app:hintTextColor="@color/white"
    android:textColorHint="@color/white"
    app:boxStrokeColor="@color/text_input_box_stroke"
    <!-- 可选:统一不同状态下的下划线宽度,默认失焦1dp、聚焦2dp
    app:boxStrokeWidth="1dp"
    app:boxStrokeWidthFocused="1dp"
    -->
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/usernameInputEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:textColor="@color/white"
        android:text="@={authViewModel._username}"/>
</com.google.android.material.textfield.TextInputLayout>

全局适配补充(可选)

如果需要让应用内所有输入框都遵循该配色规则,可以在你的App主题中添加以下配置:

<item name="textInputStyle">@style/Widget.MaterialComponents.TextInputLayout.FilledBox</item>
<item name="boxStrokeColor">@color/text_input_box_stroke</item>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:36:07