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

password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

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

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);

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

有办法实现吗?


当前回答

这招对我很管用:

mytext.setInputType(InputType.TYPE_CLASS_NUMBER);

其他回答

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

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

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

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

只是对@Rajkiran提供的正确答案的补充评论,你可能想添加

etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

切换到正常输入状态,这样用户就不会被键盘的自动提示所困扰

好吧,经过几个小时的尝试,终于实现了。下面是代码..

  buttons.get(2).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
       if(buttons.get(2).getText().toString().equalsIgnoreCase(getResources().getString(R.string.show))){
           editTexts.get(1).setInputType(InputType.TYPE_CLASS_TEXT);
           editTexts.get(1).setSelection(editTexts.get(1).getText().length());
           buttons.get(2).setText(getResources().getString(R.string.hide));
        }else{
           editTexts.get(1).setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
           //editTexts.get(1).setTransformationMethod(PasswordTransformationMethod.getInstance());
           editTexts.get(1).setSelection(editTexts.get(1).getText().length());
           buttons.get(2).setText(getResources().getString(R.string.show));
       }

    }
});

解释:-我有一个按钮与默认文本显示。 onclick事件后,它检查按钮的文本是否显示。 如果它是显示,然后改变输入类型,调整光标的位置,并设置新的文本隐藏在其中。

当它藏起来的时候……做反向,即隐藏密码,调整光标和设置文本显示。就是这样。它像魔法一样有效。

在寻找Visual Studio / Xamarin的类似解决方案时,我看到了这个帖子。下面是我使用Xamarin的方法。注意,这个实现在模式切换时保留type_text_flag_no_recommendations标志。

EditText et = FindViewById<EditText>(Resource.Id.ET);

显示字符: et.InputType = Android.Text.InputTypes.TextVariationVisiblePassword | android . text . inputtypes . textflagnosuggestion;

隐藏字符: et.InputType = Android.Text.InputTypes.TextVariationPassword | Android.Text.InputTypes.ClassText;

将位置设置为结束: int position = et.Text.Length; et.SetSelection(位置,位置);

已添加密码可见切换功能以支持库版本24.2.0,使您可以直接从EditText切换密码,而不需要复选框。

您可以首先将支持库版本更新到24.2.0,然后在TextInputEditText上设置密码的inputType。下面是如何做到这一点:

<android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/password"
            android:inputType="textPassword"/>
</android.support.design.widget.TextInputLayout>

您可以在TextInputLayout的开发人员文档中获得有关新特性的更多信息。