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

Android切换密码可见性时EditText光标跳转至起始位置如何解决

光标跳转原因

当你为EditText动态设置TransformationMethod时,Android原生控件会触发文本重绘逻辑,默认会将光标/选中位置重置到文本起始位置,属于系统控件的默认行为,不是代码逻辑错误导致。

修复方案

只需要在切换密码显隐前保存当前光标位置,设置完转换规则后手动恢复光标位置即可,修改后的逻辑代码如下:

private fun initUI() {
    binding.imgTogglePassword.setOnCheckedChangeListener { _, isChecked ->
        // 保存当前光标位置,coerceAtMost避免光标位置超出文本长度导致异常
        val currentCursorPos = binding.etPassword.selectionEnd.coerceAtMost(binding.etPassword.text?.length ?: 0)
        if (!isChecked) {
            // 隐藏密码
            binding.etPassword.transformationMethod = PasswordTransformationMethod.getInstance()
        } else {
            // 显示密码
            binding.etPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
        }
        // 恢复光标到原有位置
        binding.etPassword.setSelection(currentCursorPos)
    }
}

该方案不会影响原有密码显隐逻辑,同时完美保留切换前的光标位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:06:04