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

使用TextInputEditText时错误图标覆盖end icon该如何解决

解决方案

你的问题根源是错误地将错误状态设置到了TextInputEditText上,而非外层的TextInputLayout,绕开了TextInputLayout的内置状态管理逻辑,才会出现图标重叠,按以下两步修改即可:

1. 修改布局文件

  • 给TextInputLayout新增app:errorIconDrawable="@null"属性,隐藏系统默认的错误图标(如果需要保留错误图标,可替换为你自定义的错误图标资源,TextInputLayout会自动调整位置不会和endIcon重叠)
  • 移除TextInputEditText的自定义background属性,改为@null,避免自定义背景破坏TextInputLayout内置的间距计算规则,修改后布局代码如下:
<com.google.android.material.textfield.TextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox"
    android:id="@+id/username_label"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:startIconDrawable="@drawable/icons8_user_24"
    app:endIconMode="custom"
    app:endIconDrawable="@drawable/icons8_user_24"
    app:errorEnabled="true"
    app:errorIconDrawable="@null"
    android:hint="Enter UserName"
    android:textColorHint="@color/teal_200">

    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:inputType="text" />

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

2. 修改Java逻辑代码

将给TextInputEditText设置错误的逻辑,改为给外层TextInputLayout设置,修改后代码如下:

// 先获取TextInputLayout实例
TextInputLayout usernameLabel = findViewById(R.id.username_label);
UsereditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s != null && !isEmailAddress(s.toString())) {
            usernameLabel.setError("Error Address");
        } else {
            usernameLabel.setError(null);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

补充说明

TextInputLayout的设计逻辑就是统一接管输入框的提示、图标、错误等所有状态,内部会自动计算各个元素的位置避免重叠,所有状态操作都直接作用于TextInputLayout即可,不需要操作内部的EditText。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:24:06