使用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
相关产品推荐
相关产品推荐

