更改TextInputLayout错误字体?

7

是否可以为EditText更改TextInputLayout错误文本字体?

我只能通过app:errorTextAppearance更改颜色或文字大小。


请完整展示您尝试过的内容,这样就容易找到解决方案了。 - Androider
2个回答

7
您可以使用SpannableString来设置字体:
SpannableString s = new SpannableString(errorString);
s.setSpan(new TypefaceSpan(font), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mPasswordView.setError(s);

一个自定义的 Span 类,具有特定的 Typeface 设置:

public class TypefaceSpan extends MetricAffectingSpan {
    private Typeface mTypeface;
    public TypefaceSpan(Typeface typeface) {
        mTypeface = typeface;
    }

    @Override
    public void updateMeasureState(TextPaint p) {
        p.setTypeface(mTypeface);
        p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }

    @Override
    public void updateDrawState(TextPaint tp) {
        tp.setTypeface(mTypeface);
        tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }
}

谢谢,真的有效!我浪费了一整天的时间,以为新字体没有应用。然后我下载了一个新字体(比如https://fonts.google.com/specimen/Pacifico),发现它真的改变了。 - undefined

1
如果您喜欢的话,还有另一种方法可以设置错误颜色或字体。
public static void setErrorTextColor(TextInputLayout textInputLayout, int color, Typeface font) {
  try {
    Field fErrorView = TextInputLayout.class.getDeclaredField("mErrorView");
    fErrorView.setAccessible(true);
    TextView mErrorView = (TextView) fErrorView.get(textInputLayout);
    Field fCurTextColor = TextView.class.getDeclaredField("mCurTextColor");
    fCurTextColor.setAccessible(true);
    fCurTextColor.set(mErrorView, color);
    mErrorView.setTypeface(font);
  } catch (Exception e) {
    e.printStackTrace();
  }
}

现在出现错误:"java.lang.NoSuchFieldException: 在类Lcom/google/android/material/textfield/TextInputLayout中找不到字段mErrorView"。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接