简体   繁体   English

如何允许在 Android 中覆盖库的字体系列

[英]How to allow to override the font family of a library in Android

I have made an Android library that contains visual components.我制作了一个包含可视化组件的 Android 库。 This components style must be customizable by the main hosting application via resources files.此组件样式必须可由主托管应用程序通过资源文件进行自定义。

In order to let the font family customizable I have defined a string为了让字体系列可定制,我定义了一个字符串

<string name="customizableFontFamily" translatable="false">sans-serif</string>

Which is used in the main theme style:用于主主题风格:

<style name="MyMainTheme" parent="Theme.AppCompat.Light.NoActionBar">
   <item name="android:fontFamily">@string/customizableFontFamily</item>

This works fine when using the basic Android fonts (casual, monospace, sans-serif, etc).这在使用基本的 Android 字体(休闲、等宽、无衬线等)时效果很好。 However, if the user wants to define a custom font it does not work since it has to point to a reference:但是,如果用户想要定义自定义字体,则它不起作用,因为它必须指向引用:

<string name="customizableFontFamily" translatable="false">@font/myFont</string>

Is there any way to accomplish this?有什么办法可以做到这一点吗?

You can define a custom TextAppearance and change your ui component to work with this instead of a simple fontFamily.您可以定义自定义TextAppearance并更改您的 ui 组件以使用它而不是简单的 fontFamily。

Something like:就像是:

<style name="TextAppearance.MyApp.Headline1" parent="TextAppearance.MaterialComponents.Headline1">
  ...
  <item name="fontFamily">@font/custom_font</item>
  <item name="android:textStyle">normal</item>
  <item name="android:textAllCaps">false</item>
  <item name="android:textSize">64sp</item>
  <item name="android:letterSpacing">0</item>
  ...
</style>

In this way the apps which use your lib can customize these values.通过这种方式,使用您的库的应用程序可以自定义这些值。
Soon all components included in the Material Design Library will reference these themeable text attributes.很快,材料设计库中包含的所有组件都将引用这些可主题化的文本属性。
You can read more here .您可以在此处阅读更多内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM