EditText实现密码隐藏显示的秘密

发布时间:2024-08-31 17:35:26 作者:小樊
来源:亿速云 阅读:85

要在Android中实现EditText密码隐藏显示,你可以使用以下方法:

  1. 在XML布局文件中设置EditText的属性:
<EditText
    android:id="@+id/editTextPassword"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:hint="请输入密码" />

这里,android:inputType="textPassword"属性将密码字符显示为隐藏符号(如•)。

  1. 在Java或Kotlin代码中处理文本更改事件:

如果你想实现一个自定义的密码显示/隐藏功能,而不是使用默认的Android属性,你可以监听EditText的文本更改事件,并在用户输入时切换密码字符的显示。

Java示例:

EditText editTextPassword = findViewById(R.id.editTextPassword);

editTextPassword.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (!s.toString().isEmpty()) {
            editTextPassword.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.ic_eye_off), null);
        } else {
            editTextPassword.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.ic_eye_on), null);
        }
    }
});

Kotlin示例:

val editTextPassword = findViewById<EditText>(R.id.editTextPassword)

editTextPassword.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
    }

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
    }

    override fun afterTextChanged(s: Editable) {
        if (s.toString().isNotEmpty()) {
            editTextPassword.setCompoundDrawablesWithIntrinsicBounds(null, null, resources.getDrawable(R.drawable.ic_eye_off), null)
        } else {
            editTextPassword.setCompoundDrawablesWithIntrinsicBounds(null, null, resources.getDrawable(R.drawable.ic_eye_on), null)
        }
    }
})

这里,我们使用addTextChangedListener方法添加了一个TextWatcher,在用户输入密码时切换密码字符的显示。我们使用setCompoundDrawablesWithIntrinsicBounds方法分别设置了眼睛图标(开和关)作为密码显示/隐藏的切换。

注意:确保在你的项目中添加了眼睛图标的资源文件(如ic_eye_onic_eye_off)。你可以使用Android Studio的内置图标生成器或从其他来源添加这些图标。

推荐阅读:
  1. android基础之EditText
  2. EditText底部边框被软键盘挡住的问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

edittext

上一篇:Button控件的文本自动调整

下一篇:EditText的文本方向设置方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》