您好我想使用以下代码设置TextInputLayout字体:
public class CustomFont {
public static void setTypefaceToInputLayout(TextInputLayout inputLayout, String typeFace, Context context){
final Typeface tf = Typeface.createFromAsset(context.getAssets(), typeFace);
inputLayout.getEditText().setTypeface(tf);
try {
// Retrieve the CollapsingTextHelper Field
final Field collapsingTextHelperField = inputLayout.getClass().getDeclaredField("mCollapsingTextHelper");
collapsingTextHelperField.setAccessible(true);
// Retrieve an instance of CollapsingTextHelper and its TextPaint
final Object collapsingTextHelper = collapsingTextHelperField.get(inputLayout);
final Field tpf = collapsingTextHelper.getClass().getDeclaredField("mTextPaint");
tpf.setAccessible(true);
// Apply your Typeface to the CollapsingTextHelper TextPaint
((TextPaint) tpf.get(collapsingTextHelper)).setTypeface(tf);
} catch (Exception ignored) {
// Nothing to do
Log.e("errorXYZ","error:::"+ignored.toString());
}
}
}
该方法是用Java编写的,我从Kotlin调用它:
CustomFont.setTypefaceToInputLayout(externalView.passwordTIL,"fonts/af/dragon.ttf",context!!)
自从过去24小时以来我一直在尝试,出于某种原因,我不惜任何代价设置TextInputLayout字体(实际上是浮动提示字体)!
我一直得到以下异常:
java.lang.NoSuchFieldException: No field mCollapsingTextHelper in class Landroid/support/design/widget/TextInputLayout; (declaration of 'android.support.design.widget.TextInputLayout' appears in /data/app/com.ar.ere-2/base.apk:classes2.dex)
我不知道这个例外,但是对于我已经在我的gradle文件中启用了mutlidex的信息。那么我应该从Multidex lib中排除一些文件吗?但怎么样?
我根本不知道!
请有人请回顾一下情况!
您正在使用反射来访问不存在的字段。
TextInputLayout有一个setTypeface方法,可用于更改浮动提示和任何错误消息。