我有这个绑定适配器:
private static final String TAG = Bindings.class.getSimpleName();
private static Map<String, Typeface> typefaceCache = new HashMap<>();
@BindingAdapter({"font"})
public static void setFont(View view, String fontPath) {
Log.d(TAG, "setFont() called with: " + "view = [" + view + "], fontPath = [" + fontPath + "]");
if (view instanceof EditText) {
((EditText) view).setTypeface(getTypeface(view.getContext(), fontPath));
} else if (view instanceof TextView) {
((TextView) view).setTypeface(getTypeface(view.getContext(), fontPath));
} else if (view instanceof TextInputLayout) {
((TextInputLayout) view).setTypeface(getTypeface(view.getContext(), fontPath));
} else if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
setFont(((ViewGroup) view).getChildAt(i), fontPath);
}
}
public static Typeface getTypeface(Context ctx, String fontPath) {
Log.d(TAG, "getTypeface() called with: " + "ctx = [" + ctx + "], fontPath = [" + fontPath + "]");
AssetManager assetManager = ctx.getAssets();
Typeface typeface = typefaceCache.get(fontPath);
if (typeface == null) {
typeface = Typeface.createFromAsset(assetManager, fontPath);
typefaceCache.put(fontPath, typeface);
}
return typeface;
}
通过数据绑定,我在布局中调用font属性,如下所示:
app:font="@{Helper.BRANDON_GROTESQUE_MEDIUM}"
我正确的字体是:
public static final String BRANDON_GROTESQUE_MEDIUM = "fonts/BrandonGrotesque-Medium.otf";
还有一些日志:
06-07 18:45:55.627 2883-2883 / D / Bindings:setFont()调用:view = [android.support.v7.widget.AppCompatTextView {96d0a86 V.ED ....... ... ID 327,233-408,290#7f0c010e app:id / tv_value_units_5}],fontPath = [fonts / BrandonGrotesque-Medium.otf]
06-07 18:45:55.627 2883-2883 / D / Bindings:getTypeface()调用:ctx = [android.support.v7.widget.TintContextWrapper@ca3b6fc],fontPath = [fonts / BrandonGrotesque-Medium。 OTF]
我得到一些Typeface对象返回:
typeface = [android.graphics.Typeface@73109992]
我没有收到任何错误,但文字字体没有变化,我似乎无法找到我做错了什么。请帮助:)
更多信息:在应用程序的先前版本中,我让代码正常工作,在onCreate中设置字体。所以它实际上正在工作,Typeface的加载方式与现在的Typeface.createFromAsset相同......
现在我正在调试器中看到正在调用TextView.setTypeface。此时mLayout为空。
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_plugs, container, false);
choosePlugsViewModel();
return binding.getRoot();
}