更改editText提示的字体

Ank*_*ush 23 android android-edittext

是否可以更改EditText字段中显示的提示的字体?我想在xml本身设置字体.

fra*_*ssb 24

您可以使用SpannableString和Custom TypefaceSpan更改它.

首先,创建一个Custom TypefaceSpan类:

public class CustomTypefaceSpan extends TypefaceSpan {
    private final Typeface mNewType;

    public CustomTypefaceSpan(Typeface type) {
        super("");
        mNewType = type;
    }

    public CustomTypefaceSpan(String family, Typeface type) {
        super(family);
        mNewType = type;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        applyCustomTypeFace(ds, mNewType);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        applyCustomTypeFace(paint, mNewType);
    }

    private static void applyCustomTypeFace(Paint paint, Typeface tf) {
        int oldStyle;
        Typeface old = paint.getTypeface();
        if (old == null) {
            oldStyle = 0;
        } else {
            oldStyle = old.getStyle();
        }

        int fake = oldStyle & ~tf.getStyle();
        if ((fake & Typeface.BOLD) != 0) {
            paint.setFakeBoldText(true);
        }

        if ((fake & Typeface.ITALIC) != 0) {
            paint.setTextSkewX(-0.25f);
        }

        paint.setTypeface(tf);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将TypefaceSpan设置为SpannableString:

TypefaceSpan typefaceSpan = new CustomTypefaceSpan(typeface);
SpannableString spannableString = new SpannableString(hintText);

spannableString.setSpan(typefaceSpan, 0, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
Run Code Online (Sandbox Code Playgroud)

最后只需设置EditText的提示:

mEditText.setHint(spannableString);
Run Code Online (Sandbox Code Playgroud)


小智 5

我没有找到任何改变XML中的提示字体的有用方法.但是你可以这样做:

mEt.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.length()== 0) {
            //mEt.setTypeFace(normalFont);
        }else{
           // mEt.setTypeFace(hintFont);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
});
Run Code Online (Sandbox Code Playgroud)


Aki*_*RMS 5

有一种非常简单的方法可以做到。我刚刚在我的应用程序中做了,它奏效了。Key 也与 EditText 一起设置了 TextInputLayout 的 Facetype。

mEmailView.setTypeface(Typeface.createFromAsset(getAssets(), getString(R.string.app_font)));
((TextInputLayout) findViewById(R.id.tilEmail)).setTypeface(Typeface.createFromAsset(getAssets(), getString(R.string.app_font)));
Run Code Online (Sandbox Code Playgroud)


Sre*_*ram 2

它在 XML 中是不可能的 -

XML 中的文本和提示只能使用相同的字体。