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

如何检测TextInputLayout的endIcon是否处于选中状态?

如何检测TextInputLayout密码切换图标的选中状态?

EndCompoundLayout 内部有 isEndIconChecked() 方法可判断endIcon的选中状态,但 TextInputLayout 并未暴露这个方法。你的需求是让“重复密码”输入框仅在密码切换图标未选中(即密码处于隐藏状态)时显示,下面提供两种可行方案:

方案一:通过EditText状态直接判断(推荐)

你的临时方案思路很合理——密码切换的本质就是切换EditText的transformationMethod,所以直接通过这个状态就能判断密码是否隐藏,进而控制重复密码框的显示。可以把代码优化得更清晰:

binding.loginPassword.setEndIconOnClickListener {
    binding.loginPassword.editText?.let { editText ->
        val isPasswordHidden = editText.transformationMethod is PasswordTransformationMethod
        // 切换密码可见性
        editText.transformationMethod = if (isPasswordHidden) null else PasswordTransformationMethod.getInstance()
        // 密码隐藏时显示重复输入框
        binding.repeatPassword.isVisible = isPasswordHidden
    }
}

这种方法完全依赖公开API,没有兼容性风险,逻辑和需求直接对应,是最优解。

方案二:反射获取内部EndCompoundLayout状态(备选)

如果一定要直接获取图标的选中状态,可以用反射拿到TextInputLayout内部的EndCompoundLayout实例,再调用它的isEndIconChecked()方法。但要注意,反射依赖内部实现,Google若修改内部类结构,这个方法可能失效,仅推荐特殊场景使用:

private fun checkPasswordToggleState(textInputLayout: TextInputLayout): Boolean {
    return try {
        // 获取内部的mEndCompoundLayout字段
        val field = TextInputLayout::class.java.getDeclaredField("mEndCompoundLayout")
        field.isAccessible = true
        val endLayout = field.get(textInputLayout)
        // 调用isEndIconChecked方法
        val method = endLayout.javaClass.getDeclaredMethod("isEndIconChecked")
        method.isAccessible = true
        method.invoke(endLayout) as Boolean
    } catch (e: Exception) {
        // 反射失败时 fallback 到EditText状态判断
        e.printStackTrace()
        textInputLayout.editText?.transformationMethod is PasswordTransformationMethod
    }
}

使用示例:

binding.loginPassword.setEndIconOnClickListener {
    val isToggleChecked = checkPasswordToggleState(binding.loginPassword)
    binding.loginPassword.editText?.let {
        it.transformationMethod = if (isToggleChecked) null else PasswordTransformationMethod.getInstance()
    }
    // 未选中时显示重复输入框
    binding.repeatPassword.isVisible = !isToggleChecked
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:15:21