当EditText处于密码模式时,提示似乎以不同的字体显示(courier ?)我该如何避免这种情况?我想提示出现在相同的字体,当EditText不是在密码模式。

我当前的xml:

<EditText 
android:hint="@string/edt_password_hint"
android:layout_width="fill_parent"
android:layout_height="wrap_content" 
android:password="true"
android:singleLine="true" />

当前回答

也许是一个奇怪的例子,但我已经做过实验,并发现:

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
password.setTransformationMethod(new PasswordTransformationMethod());

改变了提示字体的大小,而不是字体本身!这仍然是一种不受欢迎的效果。奇怪的是,相反的操作:

password.setTransformationMethod(new PasswordTransformationMethod());
password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);

保持相同的字体大小。

其他回答

也许是一个奇怪的例子,但我已经做过实验,并发现:

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
password.setTransformationMethod(new PasswordTransformationMethod());

改变了提示字体的大小,而不是字体本身!这仍然是一种不受欢迎的效果。奇怪的是,相反的操作:

password.setTransformationMethod(new PasswordTransformationMethod());
password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);

保持相同的字体大小。

这就是我解决这个问题的方法。由于某些原因,我不需要设置转换方法,所以这可能是一个更好的解决方案:

在我的xml中:

<EditText
    android:id="@+id/password_edit_field"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="Password"
    android:inputType="textPassword" />

在活动中:

EditText password = (EditText) findViewById( R.id.password_edit_field );
password.setTypeface( Typeface.DEFAULT );

我使用这个解决方案来切换字体取决于提示可见性。它与Joe的答案类似,但扩展了EditText:

public class PasswordEditText extends android.support.v7.widget.AppCompatEditText {

    public PasswordEditText(Context context) {
        super(context);
    }

    public PasswordEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PasswordEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        if (text.length() > 0) setTypeface(Typeface.MONOSPACE);
        else setTypeface(Typeface.DEFAULT);
    }

}

我从对话指南中找到了这个有用的技巧

提示:默认情况下,当您将EditText元素设置为使用“textPassword”输入类型时,字体族被设置为monospace,因此您应该将其字体族更改为“sans-serif”,以便两个文本字段使用匹配的字体样式。


例如

android:fontFamily="sans-serif"

像上面一样,但要确保字段在XML中没有粗体样式,因为即使有上面的修复,它们看起来也不会相同!