较低 API 上的 androidX 自定义字体



我在我的 Kotlin 应用程序中使用 AndroidX,我一直在尝试添加自定义字体。我在res/font中有文件夹,其中包含.ttf文件和2个字体系列(v26和普通(。v26文件包含android:前缀,而另一个文件具有app:前缀。

我还在 gradle 中添加了 appcompat 和旧版支持实现,但不知何故,我仍然无法让字体在 Android 6.0 上正确显示(适用于较新的设备(。我在应用主题中将字体系列设置为:

<item name="fontFamily">@font/avalon</item>

我不知道我还能尝试什么。有人有同样的问题吗?

我认为您不能在较旧的API中将fontFamily用于自定义字体。

但是,您可以创建自己的文本视图(扩展默认文本视图(并设置自定义字体:

public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/custom.ttf");
setTypeface(tf);
}
}

}

或者像这样设置字体:

Typeface typeface=Typeface.createFromAsset(getAssets(), "fonts/custom.ttf");
myTextView.setTypeface(typeface);

最新更新