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

如何实现多个TextInputLayout密码可见性切换的联动效果

双密码输入框同步切换可见性实现方案

核心思路

两个密码输入组件共享全局可见性状态,统一处理切换事件,避免双向触发死循环。

具体实现步骤

  • 声明两个全局变量:isPasswordVisible 记录当前密码是否可见(默认false),isSyncing 作为同步锁避免循环触发事件
  • 两个TextInputLayout的app:endIconMode属性都设置为password_toggle,保留官方自带的密码切换图标样式
  • 给两个组件的EndIcon设置同一个点击事件监听器,在监听逻辑中统一处理状态更新和同步

示例代码(Kotlin):

// 初始化布局组件
val passwordLayout: TextInputLayout = findViewById(R.id.password_layout)
val confirmPwdLayout: TextInputLayout = findViewById(R.id.confirm_password_layout)

// 全局状态变量
private var isPasswordVisible = false
private var isSyncing = false

// 统一的切换点击事件
val toggleListener = View.OnClickListener {
    if (isSyncing) return@OnClickListener
    isSyncing = true
    // 翻转可见性状态
    isPasswordVisible = !isPasswordVisible
    // 统一设置两个输入框的内容显示模式
    val transformationMethod = if (isPasswordVisible) {
        HideReturnsTransformationMethod.getInstance()
    } else {
        PasswordTransformationMethod.getInstance()
    }
    passwordLayout.editText?.transformationMethod = transformationMethod
    confirmPwdLayout.editText?.transformationMethod = transformationMethod
    // 同步更新两个组件的切换图标状态
    passwordLayout.isEndIconChecked = isPasswordVisible
    confirmPwdLayout.isEndIconChecked = isPasswordVisible
    // 光标移到输入内容末尾,避免位置跳变
    passwordLayout.editText?.let { et ->
        et.setSelection(et.text.length)
    }
    confirmPwdLayout.editText?.let { et ->
        et.setSelection(et.text.length)
    }
    isSyncing = false
}

// 给两个组件绑定同一个监听器
passwordLayout.setEndIconOnClickListener(toggleListener)
confirmPwdLayout.setEndIconOnClickListener(toggleListener)

注意事项

  • 不要使用TextInputLayout自带的默认切换逻辑,必须自己重写EndIcon的点击事件才能实现同步
  • isSyncing锁是必要配置,否则状态同步时会反复触发两个组件的点击事件造成死循环
  • Java实现逻辑完全一致,仅需替换对应语法即可

内容的提问来源于stack exchange,提问作者Mehmet Taş

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:36:03