更改 TextInputLayout 错误字体?
Change TextInputLayout error font?
是否可以更改 EditText 的 TextInputLayout 错误文本字体?
我只能通过 app:errorTextAppearance 更改颜色或文字大小。
您可以使用SpannableString
来设置字体:
SpannableString s = new SpannableString(errorString);
s.setSpan(new TypefaceSpan(font), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mPasswordView.setError(s);
具有特定 Typeface
集的自定义 Span
class:
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);
}
}
另一种方法,如果你喜欢,你可以设置错误颜色或字体两者
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();
}
}
是否可以更改 EditText 的 TextInputLayout 错误文本字体?
我只能通过 app:errorTextAppearance 更改颜色或文字大小。
您可以使用SpannableString
来设置字体:
SpannableString s = new SpannableString(errorString);
s.setSpan(new TypefaceSpan(font), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mPasswordView.setError(s);
具有特定 Typeface
集的自定义 Span
class:
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);
}
}
另一种方法,如果你喜欢,你可以设置错误颜色或字体两者
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();
}
}