preloaded_fonts 未在任何布局中指定时无法以编程方式工作

preloaded_fonts does not work programatically when not specified in any layout

使用 android 工作室(基于 )添加可下载字体后,我无法以编程方式加载添加的字体。

ResourcesCompat.getFont(context, R.font.roboto)

导致以下错误

android.content.res.Resources$NotFoundException: Font resource ID #0x7f080009
at android.support.v4.content.res.ResourcesCompat.loadFont(ResourcesCompat.java:218)
at android.support.v4.content.res.ResourcesCompat.getFont(ResourcesCompat.java:196)

但是一旦我在某些布局文件中指定了相同的字体,例如

android:fontFamily="@font/roboto"

有效。

它现在也开始以编程方式工作。

为了以编程方式访问字体,您需要创建字体请求。

阅读 this 官方文档。

如果您认为这是一个冗长的过程,您可以随时在 xml 中指定它,如果不需要视图,则将其可见性设置为“消失”。