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

Android 如何修改EditText获取焦点时的下划线颜色

嘿,这个需求很常见,我来给你分享几种修改EditText焦点下划线颜色的实用方法,你可以根据自己的场景选合适的:

修改EditText焦点下划线颜色的几种方案

方法一:直接用XML属性快速设置(API 21+)

这是最省心的方式,直接在布局里给EditText添加android:backgroundTint属性就能指定焦点时的下划线颜色:

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:backgroundTint="#FF4081" /> <!-- 替换成你想要的颜色值即可 -->

如果要兼容API 21以下的版本,改用app:backgroundTint,记得先在布局根节点引入AppCompat命名空间:

xmlns:app="http://schemas.android.com/apk/res-auto"

然后设置:

app:backgroundTint="#FF4081"

方法二:自定义样式统一控制

如果想让所有EditText都用同一种样式,或者需要区分焦点/非焦点状态的颜色,可以在styles.xml里定义自定义样式:

<style name="CustomEditTextStyle" parent="Widget.AppCompat.EditText">
    <item name="colorControlActivated">#FF4081</item> <!-- 焦点状态下的下划线颜色 -->
    <item name="colorControlNormal">#9E9E9E</item> <!-- 非焦点状态的下划线颜色(可选) -->
</style>

之后在布局里给单个EditText应用样式:

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/CustomEditTextStyle" />

要是想全局生效,直接把这个样式配置到App主题里:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="editTextStyle">@style/CustomEditTextStyle</item>
</style>

方法三:代码动态修改(适合动态变色场景)

如果需要在运行时根据业务逻辑切换下划线颜色,用代码实现也很简单:

Java版本

EditText editText = findViewById(R.id.editText);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    editText.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#FF4081")));
} else {
    // 低版本兼容,需确保EditText是AppCompatEditText
    AppCompatEditText appCompatEditText = (AppCompatEditText) editText;
    appCompatEditText.setSupportBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#FF4081")));
}

Kotlin版本

val editText = findViewById<EditText>(R.id.editText)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    editText.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#FF4081"))
} else {
    (editText as AppCompatEditText).supportBackgroundTintList = ColorStateList.valueOf(Color.parseColor("#FF4081"))
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:20:05