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

Android Studio中调整TextInputLayout密码显隐切换按钮大小

问题描述

当前密码输入框的显隐切换按钮尺寸过大,需要调整为更小的尺寸,效果参考截图:
密码输入框显隐按钮尺寸过大截图
当前实现的布局代码如下:

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/password_field"
    android:layout_width="272dp"
    android:layout_height="31dp"
    android:background="@drawable/email_password_filler"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.504"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.208"
    app:passwordToggleEnabled="true"
    tools:ignore="Autofill,RtlSymmetry,TextFields">
    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/email_password_filler"
        android:hint="@string/enter_your_password"
        android:paddingStart="20sp"
        android:paddingTop="10sp"
        android:paddingBottom="5sp"
        android:textSize="13sp">

    </com.google.android.material.textfield.TextInputEditText>
</com.google.android.material.textfield.TextInputLayout>
解决方案

TextInputLayout自带的密码显隐按钮默认走Material组件的内置图标尺寸规范,要缩小尺寸直接用下面两种方法即可:

  • 方法一:用内置属性直接改尺寸
    不需要额外写自定义布局,直接在TextInputLayout节点下加属性控制图标大小和边距:
    <!-- 自定义图标尺寸,按需调整数值,比如设为20dp就会比默认尺寸小一圈 -->
    app:passwordToggleDrawableSize="20dp"
    <!-- 调整图标距输入框边缘的内边距,避免图标缩小后布局错位 -->
    app:endIconPadding="4dp"
    
    如果你用的Material依赖版本在1.7.0及以上,密码切换按钮已经统一归为尾部图标管理,也可以用app:endIconSize="20dp"设置尺寸,效果和上面的属性完全一致。
  • 方法二:自定义切换图标(适配全版本)
    如果内置属性调整后还是达不到你要的效果,可以自己做对应尺寸的图标替换默认素材:
    1. 准备好对应小尺寸的密码可见、不可见两个状态的图标,放到项目drawable目录下
    2. 新建状态选择器文件pwd_toggle_selector.xml:
      <?xml version="1.0" encoding="utf-8"?>
      <selector xmlns:android="http://schemas.android.com/apk/res/android">
          <item android:drawable="@drawable/ic_pwd_show" android:state_checked="true" />
          <item android:drawable="@drawable/ic_pwd_hide" android:state_checked="false" />
      </selector>
      
    3. 在TextInputLayout中引用这个自定义选择器替换默认图标:
      app:passwordToggleDrawable="@drawable/pwd_toggle_selector"
      
    这种方式可以完全控制图标的尺寸、样式,自由度最高。

补充提醒:你当前给TextInputLayout设置的高度只有31dp,远低于Material组件推荐的最小点击区域尺寸(48dp),就算缩小图标,也会存在点击区域过小、交互不灵敏的问题,条件允许的话建议把输入框高度调整到40dp以上,使用体验会好很多。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 02:54:20