当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" />

当前回答

解决这个问题有很多方法,但每种方法都有优缺点。下面是我的测试

我只面对这个字体问题在某些设备(列表在我的答案)时启用输入密码由

edtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

如果我使用android:inputType="textPassword",这个问题不会发生

我曾经尝试过

1)使用setTransformationMethod代替inputType

edtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());

字体效果会很好 键盘显示不太好(只能显示文本,不能在文本上方显示数字)

2)使用字体。默认的

setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
setTypeface(Typeface.DEFAULT);

键盘显示良好, 字体可能工作不太好。示例sans-serif-light是我的应用程序中所有视图的默认字体= setTypeface(Typeface.DEFAULT)后面的>,EditText字体在某些设备中仍然看起来不同

3)使用android:fontFamily="sans-serif"

对于一些设备,它会崩溃,检查我的答案在这里https://stackoverflow.com/a/52421199/5381331。字体看起来也不一样

我的解决方案

在setInputType之前缓存字体,然后重用它

Typeface cache = edtPassword.getTypeface();
edtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
edtPassword.setTypeface(cache);

测试 一些设备面临字体问题

小米A2 (8.0.1) Pixel XL (8.1.0) Sony Xperia Z5 Au (SOV32) (6.0) 箭NX (F-04G) (6.0.1) 京瓷(S2) (7.0)

一些设备不面临字体问题

三星S4 (SC-04E) (5.0.1) 三星Galaxy Node 5 (5.1.1) 三星S7 Edge (SM-G935F) (7.0)

其他回答

使用书法图书馆。

然后它仍然不会用正确的字体更新密码字段。所以在代码中,而不是在xml中:

Typeface typeface_temp = editText.getTypeface();
editText.setInputType(inputType); /*whatever inputType you want like "TYPE_TEXT_FLAG_NO_SUGGESTIONS"*/
//font is now messed up ..set it back with the below call
editText.setTypeface(typeface_temp); 

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

在我的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 );

这是如何使输入密码有提示,不转换为*和默认字体!!

关于XML:

android:inputType="textPassword"
android:gravity="center"
android:ellipsize="start"
android:hint="Input Password !."

活动介绍:

inputPassword.setTypeface(Typeface.DEFAULT);

感谢芒果和rjjr的洞察力:D。

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

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


例如

android:fontFamily="sans-serif"

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

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

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

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

保持相同的字体大小。