简体   繁体   中英

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

I have made an Android library that contains visual components. 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). 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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