You need to enable JavaScript to run this app. 如何修改TextInputLayout中TextInputEditText的光标颜色
优惠活动
大模型
产品
解决方案
定价
更多

如何修改TextInputLayout中TextInputEditText的光标颜色

enter image description here

如何修改TextInputEditText的光标颜色。
我已尝试使用textcursordrawable进行设置,但并未生效,提前感谢各位的解答。

解决方案

textCursorDrawable未生效通常是外层TextInputLayout的Material主题默认配置覆盖了属性设置,可按照以下优先级选择适配方案:

方案1:全局主题统一配置(推荐)

适合所有输入框统一调整样式,在res/values/styles.xml中自定义TextInputLayout样式:

<style name="AppTextInputLayoutStyle" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
    <!-- 同时控制光标、浮标签、激活态下划线颜色,无需单独配置光标 -->
    <item name="colorControlActivated">@color/你的目标颜色</item>
</style>

布局文件中给外层TextInputLayout引用该样式即可:

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/til_content"
    style="@style/AppTextInputLayoutStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="输入内容">

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

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

方案2:单独自定义光标样式

如果需要和激活态主题色区分,单独修改光标颜色:

  • 在res/drawable目录下新建光标样式文件custom_edit_cursor.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/你的目标颜色" />
    <size android:width="2dp" />
</shape>
  • 给TextInputEditText配置该样式,同时加backgroundTint属性避免主题覆盖:
<com.google.android.material.textfield.TextInputEditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:backgroundTint="@null"
    android:textCursorDrawable="@drawable/custom_edit_cursor" />

方案3:代码动态修改

运行时需要动态调整光标颜色可使用以下代码:

// Kotlin示例
val editText = findViewById<TextInputEditText>(R.id.et_content)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
    editText.textCursorDrawable?.setTint(ContextCompat.getColor(this, R.color.target_color))
}

内容的提问来源于stack exchange,提问作者R Suman Radhakrishnan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 09:06:09