如何为Material TextInputLayout添加两个endIcon尾部图标
可行实现方案
下面给你两种经过验证的实现方式,不需要依赖第三方方案:
方案1:自定义endIcon布局(最便捷,适配原生Material样式)
原生TextInputLayout的endIcon支持传入自定义View,你可以直接将两个图标封装到一个自定义布局里,替换原来的系统密码切换图标即可:
- 首先新建图标布局
res/layout/item_double_end_icons.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal" android:gravity="center_vertical" android:paddingEnd="16dp"> <!-- 第一个图标:密码切换 --> <ImageView android:id="@+id/iv_pwd_toggle" android:layout_width="24dp" android:layout_height="24dp" android:layout_marginEnd="12dp" android:src="@drawable/ic_eye_off" android:background="?attr/selectableItemBackgroundBorderless"/> <!-- 第二个图标:自定义功能 --> <ImageView android:id="@+id/iv_custom_action" android:layout_width="24dp" android:layout_height="24dp" android:src="@drawable/ic_your_custom_icon" android:background="?attr/selectableItemBackgroundBorderless"/> </LinearLayout>
- 修改你现有TextInputLayout的XML配置,移除自带的密码切换模式:
<com.google.android.material.textfield.TextInputLayout android:id="@+id/tilPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/ed_password_label" app:endIconMode="custom" app:errorEnabled="true"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/etPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:imeOptions="actionDone" android:inputType="textPassword" /> </com.google.android.material.textfield.TextInputLayout>
- 在页面代码中加载自定义布局,绑定点击逻辑:
// 加载自定义尾部图标布局 val endIconsView = LayoutInflater.from(this).inflate(R.layout.item_double_end_icons, tilPassword, false) tilPassword.endIconView = endIconsView // 密码切换逻辑 val ivPwdToggle = endIconsView.findViewById<ImageView>(R.id.iv_pwd_toggle) ivPwdToggle.setOnClickListener { val isPwdVisible = etPassword.transformationMethod == HideReturnsTransformationMethod.getInstance() etPassword.transformationMethod = if (isPwdVisible) { PasswordTransformationMethod.getInstance() } else { HideReturnsTransformationMethod.getInstance() } ivPwdToggle.setImageResource(if (isPwdVisible) R.drawable.ic_eye_off else R.drawable.ic_eye) etPassword.setSelection(etPassword.text?.length ?: 0) } // 第二个图标自定义逻辑 val ivCustom = endIconsView.findViewById<ImageView>(R.id.iv_custom_action) ivCustom.setOnClickListener { // 这里写你需要的操作,比如跳转帮助页、清空输入等 }
方案2:自定义TextInputLayout子类(适合多场景复用)
如果多个输入框都需要双尾部图标,可以自定义TextInputLayout子类,重写onMeasure、onLayout方法固定第二个图标的位置,封装图标点击、样式适配逻辑,避免每个页面重复写代码。
注意事项
- 自定义图标建议使用24*24dp的尺寸,和Material设计规范对齐
- 图标添加
?attr/selectableItemBackgroundBorderless背景可以实现默认的点按水波纹效果 - 记得给图标添加contentDescription,满足无障碍适配要求
内容的提问来源于stack exchange,提问作者Nikita Kalugin
相关产品推荐
相关产品推荐

