260

当 EditText 处于密码模式时,提示似乎以不同的字体显示(信使?)。我怎样才能避免这种情况?我希望提示以与 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" />
4

18 回答 18

400

更改 xml 中的字体也不适用于我的提示文本。我找到了两种不同的解决方案,其中第二种对我来说有更好的表现:

1)android:inputType="textPassword"从你的xml文件中删除,而是在java中设置它:

EditText password = (EditText) findViewById(R.id.password_text);
password.setTransformationMethod(new PasswordTransformationMethod());

使用这种方法,提示字体看起来不错,但是当您在该编辑字段中输入时,您看不到纯文本中的每个字符,然后才变成密码点。此外,全屏输入时,不会出现圆点,而是以明文形式显示密码。

2)留android:inputType="textPassword"在你的xml中。在 Java 中,还设置字体和密码方法:

EditText password = (EditText) findViewById(R.id.register_password_text);
password.setTypeface(Typeface.DEFAULT);
password.setTransformationMethod(new PasswordTransformationMethod());

这种方法给了我想要的提示字体,并给了我想要的密码点行为。

希望有帮助!

于 2010-08-09T23:13:46.067 回答
196

我从Dialogs Guide中找到了这个有用的提示

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


例如

android:fontFamily="sans-serif"
于 2013-08-06T07:15:47.930 回答
32

这就是我为解决这个问题所做的。出于某种原因,我不必设置转换方法,所以这可能是一个更好的解决方案:

在我的 xml 中:

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

在我的Activity

EditText password = (EditText) findViewById( R.id.password_edit_field );
password.setTypeface( Typeface.DEFAULT );
于 2012-09-17T16:39:53.940 回答
22

setTransformationMethod 方法为我打破了 android:imeOption,并允许在密码字段中输入回车。相反,我正在这样做:

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

而且我没有在 XML 中设置 android:password="true" 。

于 2012-01-03T19:38:51.327 回答
5

manisha 提供的答案确实有效,但与默认值相比,它使密码字段处于非标准状态。也就是说,默认字体也适用于密码字段,包括点替换和在被点替换之前出现的预览字符(以及当它是“可见密码”字段时)。

要解决此问题并使其 1) 外观和行为与默认textPassword输入类型完全相同,而且 2) 允许提示文本以默认(非等宽)字体显示,您需要TextWatcher在字段上设置一个可以切换fontface 之间正确来回Typeface.DEFAULTTypeface.MONOSPACE基于它是否为空。我创建了一个辅助类,可用于完成此任务:

import android.graphics.Typeface;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

/**
 * This class watches the text input in a password field in order to toggle the field's font so that the hint text
 * appears in a normal font and the password appears as monospace.
 *
 * <p />
 * Works around an issue with the Hint typeface.
 *
 * @author jhansche
 * @see <a
 * href="http://stackoverflow.com/questions/3406534/password-hint-font-in-android">http://stackoverflow.com/questions/3406534/password-hint-font-in-android</a>
 */
public class PasswordFontfaceWatcher implements TextWatcher {
    private static final int TEXT_VARIATION_PASSWORD =
            (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
    private TextView mView;

    /**
     * Register a new watcher for this {@code TextView} to alter the fontface based on the field's contents.
     *
     * <p />
     * This is only necessary for a textPassword field that has a non-empty hint text. A view not meeting these
     * conditions will incur no side effects.
     *
     * @param view
     */
    public static void register(TextView view) {
        final CharSequence hint = view.getHint();
        final int inputType = view.getInputType();
        final boolean isPassword = ((inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION))
                == TEXT_VARIATION_PASSWORD);

        if (isPassword && hint != null && !"".equals(hint)) {
            PasswordFontfaceWatcher obj = new PasswordFontfaceWatcher(view);
            view.addTextChangedListener(obj);

            if (view.length() > 0) {
                obj.setMonospaceFont();
            } else {
                obj.setDefaultFont();
            }
        }
    }

    public PasswordFontfaceWatcher(TextView view) {
        mView = view;
    }

    public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
        // Not needed
    }

    public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
        if (s.length() == 0 && after > 0) {
            // Input field went from empty to non-empty
            setMonospaceFont();
        }
    }

    public void afterTextChanged(final Editable s) {
        if (s.length() == 0) {
            // Input field went from non-empty to empty
            setDefaultFont();
        }
    }

    public void setDefaultFont() {
        mView.setTypeface(Typeface.DEFAULT);
    }

    public void setMonospaceFont() {
        mView.setTypeface(Typeface.MONOSPACE);
    }
}

然后要使用它,您需要做的就是调用register(View)静态方法。其他一切都是自动的(包括在视图不需要时跳过解决方法!):

    final EditText txtPassword = (EditText) view.findViewById(R.id.txt_password);
    PasswordFontfaceWatcher.register(txtPassword);
于 2013-07-10T22:32:46.240 回答
5

有很多方法可以解决这个问题,但每种方法都有利有弊。这是我的测试

通过_

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

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

我尝试过的东西

1)setTransformationMethod改为使用inputType

edtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
  • 字体会很好用
  • 键盘显示不太好(它只显示文本,不在文本顶部显示数字)

2) 使用Typeface.DEFAULT

setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
setTypeface(Typeface.DEFAULT);
  • 键盘显示不错
  • 字体可能效果不佳。示例sans-serif-light是我的应用程序中所有的默认字体View=> after setTypeface(Typeface.DEFAULT),该EditText字体在某些设备中看起来仍然不同

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

我的解决方案

setInputType在重用之前缓存字体

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

测试
一些设备的字体问题

  • 小米 A2 (8.0.1)
  • 像素 XL (8.1.0)
  • 索尼 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)
于 2018-09-05T02:43:43.177 回答
4

对于大多数情况,其他答案是正确的解决方案。

但是,如果您使用自定义EditText子类来默认应用自定义字体,则会出现一个微妙的问题。如果你在子类的构造函数中设置了自定义字体,如果你设置了inputType="textPassword".

在这种情况下,请将您的样式移至通话onAttachedToWindow后。super.onAttachedToWindow

示例实现:

package net.petosky.android.ui;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.EditText;

/**
 * An EditText that applies a custom font.
 *
 * @author cory@petosky.net
 */
public class EditTextWithCustomFont extends EditText {

    private static Typeface customTypeface;

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

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

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

    /**
     * Load and store the custom typeface for this app.
     *
     * You should have a font file in: project-root/assets/fonts/
     */
    private static Typeface getTypeface(Context context) {
        if (customTypeface == null) {
            customTypeface = Typeface.createFromAsset(
                    context.getAssets(), "fonts/my_font.ttf");
        }
        return customTypeface;
    }

    /**
     * Set a custom font for our EditText.
     *
     * We do this in onAttachedToWindow instead of the constructor to support
     * password input types. Internally in TextView, setting the password
     * input type overwrites the specified typeface with the system default
     * monospace.
     */
    @Override protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        // Our fonts aren't present in developer tools, like live UI
        // preview in AndroidStudio.
        if (!isInEditMode()) {
            setTypeface(getTypeface(getContext()));
        }
    }
}
于 2015-02-26T20:05:27.727 回答
3

InputType我知道这可能是较旧的,但是当我一起使用时,我遇到了与此问题相关的事情app:passwordToggleEnabled="true"

所以,写这个,因为它可以帮助这里的人。

我想对密码字段使用自定义字体以及app:passwordToggleEnabled密码输入字段的选项。但在 27.1.1(编写此代码时)支持库中,它崩溃了。

所以代码如下所示,

<android.support.design.widget.TextInputLayout
        android:id="@+id/input_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/_10dp"
        android:layout_marginTop="@dimen/_32dp"
        android:hint="@string/current_password"
        android:textColorHint="@color/hint_text_color"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:passwordToggleEnabled="true"
        app:passwordToggleTint="@color/black">


        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start|left"
            android:maxLines="1"
            android:textAlignment="viewStart"
            android:textColor="@color/black"
            android:textColorHint="@color/camel"
            android:textSize="@dimen/txt_16sp"
            app:font_style="regular"
            app:drawableEnd="@drawable/ic_remove_eye" />

    </android.support.design.widget.TextInputLayout>

上面的代码没有inputType在 XML 中定义

EditText password = (EditText) findViewById(R.id.password);
password.setTransformationMethod(new PasswordTransformationMethod());

在 Java 中,setTransformationMethod它将帮助我获得textPassword输入类型的属性,并且我很高兴我的自定义字体样式。

但是下面提到的崩溃发生在所有具有 27.1.1 支持库的 API 级别。

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.support.design.widget.CheckableImageButton.setChecked(boolean)”

这是由于 onRestoreInstanceState内部TextInputLayout课程而崩溃的。

重现步骤:切换密码可见性并最小化应用程序并从最近的应用程序中打开。呃,ho 崩溃了!

我只需要默认密码切换选项(使用支持库)和密码输入字段中的自定义字体。

一段时间后,通过以下方式弄清楚,

<android.support.design.widget.TextInputLayout
        android:id="@+id/input_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/_10dp"
        android:layout_marginTop="@dimen/_32dp"
        android:hint="@string/current_password"
        android:textColorHint="@color/hint_text_color"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:passwordToggleEnabled="true"
        app:passwordToggleTint="@color/black">


        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start|left"
            android:maxLines="1"
            android:textAlignment="viewStart"
            android:textColor="@color/black"
            android:textColorHint="@color/camel"
            android:textSize="@dimen/txt_16sp"
            app:font_style="regular"
            app:drawableEnd="@drawable/ic_remove_eye"
            android:inputType="textPassword" />

    </android.support.design.widget.TextInputLayout>

在 XML 中,添加android:inputType="textPassword"

TextInputLayout inputPassword = findViewById(R.id.input_password);
EditText password = findViewById(R.id.password);
EditText userName = findViewById(R.id.user_name);
// Get the typeface of user name or other edit text
Typeface typeface = userName.getTypeface();
if (typeface != null)
   inputLayout.setTypeface(typeface); // set to password text input layout

在上面的java代码中,

我从用户名中获取了自定义字体EditText并将其应用于TextInputLayout密码字段。现在您不需要将字体显式设置为密码EditText,因为它将获取该TextInputLayout属性。

另外,我删除了password.setTransformationMethod(new PasswordTransformationMethod());

通过这种方式,passwordToggleEnabled正在工作,自定义字体也被应用并且再见到崩溃。希望这个问题将在即将发布的支持版本中得到解决。

于 2018-07-06T07:48:37.127 回答
2

您还可以使用自定义小部件。它非常简单,不会弄乱您的 Activity/Fragment 代码。

这是代码:

public class PasswordEditText extends EditText {

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

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

  }

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

  private void init() {
    setTypeface(Typeface.DEFAULT);
  }
}

您的 XML 将如下所示:

<com.sample.PasswordEditText
  android:id="@+id/password_edit_field"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:hint="Password"
  android:inputType="textPassword"
  android:password="true" />
于 2013-06-04T19:35:13.817 回答
2

使用书法库

那么它仍然不会使用正确的字体更新密码字段。所以在代码中而不是在 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); 
于 2017-02-27T23:46:09.337 回答
0

我最近添加了将切换等宽空间打开/关闭更改为 EditText 的扩展的功能,专门用于密码,它可能对某些人有所帮助。它不使用android:fontFamily所以兼容<16。

于 2016-01-06T09:42:49.087 回答
0

您还可以使用

<android.support.design.widget.TextInputLayout/>

和...一起

<android.support.v7.widget.AppCompatEditText/>
于 2017-02-22T14:31:37.593 回答
0

我使用此解决方案根据提示可见性切换字体。它类似于 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);
    }

}
于 2017-03-25T14:18:06.803 回答
0

如果您将书法库与 TextInputLayout 和 EditText 结合使用,则以下代码可以正常工作。

    EditText password = (EditText) findViewById(R.id.password);
    TextInputLayout passwordLayout = (TextInputLayout) findViewById(R.id.passwordLayout);

    Typeface typeface_temp = password.getTypeface();
    password.setInputType(InputType.TYPE_CLASS_TEXT |
            InputType.TYPE_TEXT_VARIATION_PASSWORD); 

    password.setTypeface(typeface_temp);
    passwordLayout.setTypeface(typeface_temp);
于 2017-05-24T20:02:06.457 回答
0

也许是一个奇怪的案例,但我已经对此进行了实验并发现:

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

改变了提示字体的大小而不是字体本身!这仍然是不希望的效果。奇怪的是,反向操作:

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

保持相同的字体大小。

于 2017-09-01T03:45:28.250 回答
0

我找到了解决这个问题的可靠方法

打招呼的最佳方式,我找到了解决此问题的可靠方法

最好的方法是创建一个自定义的 editText 并将 typeface 的值保存为 temp 然后将该方法应用于 InputType 更改,最后我们将 temp type face 的值设置回 editText。像这样:

public class AppCompatPasswordEditText extends AppCompatEditText {


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

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

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


    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        // Our fonts aren't present in developer tools, like live UI
        // preview in AndroidStudio.
        Typeface cache = getTypeface();

        if (!isInEditMode() && cache != null) {
            setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            setTypeface(cache);
        }
    }

}
于 2019-05-01T17:50:26.097 回答
-1

这是如何制作具有未转换为 * 和默认字体的提示的输入密码!!。

在 XML 上:

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

活动:

inputPassword.setTypeface(Typeface.DEFAULT);

感谢:mango 和 rjrjr 的洞察力:D。

于 2013-10-11T06:13:39.050 回答
-2

与上面类似,但请确保字段在 xml 中没有粗体样式,因为即使经过上述修复,它们看起来也永远不会相同!

于 2010-10-29T11:28:45.483 回答