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

Kotlin中如何修改TextField焦点颜色?自定义EditText后仍为红色

在Kotlin中修改TextField/EditText焦点颜色的方法

一、Jetpack Compose 中的 TextField

直接通过 TextFieldDefaults.textFieldColors 自定义焦点相关颜色,包括下划线、标签、光标等:

var text by remember { mutableStateOf("") }

TextField(
    value = text,
    onValueChange = { text = it },
    label = { Text("输入内容") },
    colors = TextFieldDefaults.textFieldColors(
        focusedIndicatorColor = Color.Green, // 焦点状态下的下划线颜色
        focusedLabelColor = Color.Green,     // 焦点状态下的标签文字颜色
        cursorColor = Color.Green            // 光标颜色(可选)
    )
)

二、传统 Android View 中的 EditText

如果使用的是传统布局的 EditText,可通过以下两种方式修改焦点颜色:

方法1:自定义 Drawable Selector

创建一个状态选择器 drawable 文件(如 edittext_focus_selector.xml),定义焦点和非焦点状态的样式:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 焦点状态 -->
    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent" />
            <stroke android:width="2dp" android:color="#00FF00" /> <!-- 焦点边框颜色 -->
            <corners android:radius="4dp" />
        </shape>
    </item>
    <!-- 默认状态 -->
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent" />
            <stroke android:width="1dp" android:color="#CCCCCC" /> <!-- 默认边框颜色 -->
            <corners android:radius="4dp" />
        </shape>
    </item>
</selector>

在布局中给 EditText 设置该背景:

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/edittext_focus_selector"
    android:padding="8dp" />

方法2:修改主题属性

通过自定义主题修改 colorControlActivated(焦点状态颜色),可全局或单个应用:

在 styles.xml 中定义自定义主题:

<style name="CustomEditTextTheme" parent="Widget.MaterialComponents.EditText">
    <item name="colorControlActivated">#00FF00</item> <!-- 焦点颜色 -->
    <item name="colorControlNormal">#CCCCCC</item>   <!-- 正常状态颜色 -->
</style>

在布局中为 EditText 应用该主题:

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

如果之前自定义 EditText 未生效,检查是否正确应用了上述样式或主题,若使用 Material Components 库,需确保主题继承自 Material 相关样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:38:14