在我的应用程序中,我有一个EditText,其默认输入类型设置为android:inputType="textPassword"默认。它的右侧有一个复选框,选中该复选框时,将该编辑文本的输入类型更改为普通纯文本。它的代码是

password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

我的问题是,当复选框未选中时,它应该再次设置输入类型为密码。我用过-

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);

但是,编辑文本中的文本仍然可见。令人惊讶的是,当我改变方向时,它会自动将输入类型设置为PASSWORD,其中的文本是项目符号(显示为密码)。

有办法实现吗?


当前回答

我会删除android:inputType="textPassword"从你的布局。这就是为什么当方向改变时,它会切换回密码。因为每次方向改变,视图都会被重新创建。

对于第一个问题,试试这个:

String text = password.getText();
password.setText("");
password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
password.setText(text);

基本上是在你改变输入类型之前清空文本,然后再把它加回来。

其他回答

这招对我很管用:

mytext.setInputType(InputType.TYPE_CLASS_NUMBER);

这是图像/按钮显示/隐藏密码的完整onClick处理程序。

    new OnClickListener() {
        @Override
        public void onClick(View v) {
            // current ursor position
            int cursorPosition = edtPassword.getSelectionStart();

            // toggles the control variable
            isPassworsVisible = !isPassworsVisible;

            // sets the image toggler inside edit text
            passwordVisible.setImageDrawable(getResources().getDrawable(isPassworsVisible ? R.drawable.ic_eye_checked : R.drawable.ic_eye_unchecked));

            // apply input type
            edtPassword.setInputType(isPassworsVisible ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

            // returns cursor to position
            edtPassword.setSelection(cursorPosition);
        }
    };

etPost.setInputType (InputType。TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);

从支持库v24.2.0开始。你可以很容易地做到这一点

你需要做的就是:

Add the design library to your dependecies dependencies { compile "com.android.support:design:25.1.0" } Use TextInputEditText in conjunction with TextInputLayout <android.support.design.widget.TextInputLayout android:id="@+id/etPasswordLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:passwordToggleEnabled="true"> <android.support.design.widget.TextInputEditText android:id="@+id/etPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/password_hint" android:inputType="textPassword"/> </android.support.design.widget.TextInputLayout>

passwordToggleEnabled属性将显示密码切换

在你的根布局中,不要忘记添加xmlns:app="http://schemas.android.com/apk/res-auto" 您可以使用以下方法自定义密码切换:

app:passwordToggleDrawable -可绘制的使用作为密码输入可见切换图标。 app:passwordToggleTint -用于密码输入可见切换的图标。 app:passwordToggleTintMode -用于应用背景色调的混合模式。

更多细节在TextInputLayout文档。

对于kotlin用户:

password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD