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

Xamarin.Android:如何通过代码修改单个EditText的Holo下划线颜色?

提问:编程修改单个EditText的Holo下划线颜色失败,求解决办法

我折腾了好久,想通过代码修改单个EditText的Holo下划线颜色,试了Stack Overflow上各种方法都没效果,心态有点崩了😩

我最新尝试的代码是这个,完全没反应:

txtName.Background.SetTint(Resource.Color.colorRed)

这是我的EditText的XML代码:

<EditText
    android:id="@+id/txtName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="请输入姓名"
    android:theme="@android:style/Theme.Holo.Light" />

附上我想要修改的下划线效果截图:
目标红色下划线EditText

有没有大佬能指点下,到底哪里出问题了?怎么才能成功修改这个下划线颜色?


回答:亲测可行的解决方案

终于搞定了!之前直接用Background.SetTint()没用,是因为Holo主题下EditText的下划线是作为GradientDrawable的描边存在的,直接给整个背景设 tint 不会生效,得精准定位到这个描边Drawable来修改。

最终可行的代码(以Xamarin.Android为例,对应你用的语法):

// 获取EditText的背景Drawable
var bgDrawable = txtName.Background;
// 强转为GradientDrawable(Holo下划线的实际载体)
if (bgDrawable is GradientDrawable gradientDrawable)
{
    // 将dp转换为px,保证描边宽度在不同设备上一致
    int strokeWidth = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 1, Resources.DisplayMetrics);
    // 获取目标颜色值,适配高版本Android
    int redColor = ContextCompat.GetColor(this, Resource.Color.colorRed);
    // 设置描边的宽度和颜色
    gradientDrawable.SetStroke(strokeWidth, redColor);
}

如果是原生Android Java开发,代码逻辑完全一致:

Drawable bgDrawable = txtName.getBackground();
if (bgDrawable instanceof GradientDrawable) {
    int strokeWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics());
    int redColor = ContextCompat.getColor(this, R.color.colorRed);
    ((GradientDrawable) bgDrawable).setStroke(strokeWidth, redColor);
}

关键点说明:

  • 必须把背景Drawable强转为GradientDrawable,Holo主题的EditText下划线是通过这个类的描边属性实现的
  • 用SetStroke()直接设置描边参数,比全局 tint 更精准,不会影响其他背景元素
  • 使用ContextCompat.GetColor()获取颜色,避免因API版本差异导致的过时问题

这样修改后,EditText的下划线就会变成你想要的红色啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:22:37