Skip to content

Library overrides theme's android:fontFamily #2812

Open
@nikclayton

Description

@nikclayton

About this issue

The library overrides/ignores the theme's android:fontFamily, making it more difficult than it should be to use custom font families in an app using the library.

My app (https://pachli.app) allows the user to set a custom font. This is achieved by providing a number of different styles that override android:fontFamily, and applying the correct style at runtime based on the value of a user's preference.

For example, in styles.xml:

<style name="FontAtkinsonHyperlegible">
    <item name="android:fontFamily">@font/atkinson_hyperlegible</item>
</style>

<style name="FontEstedad">
    <item name="android:fontFamily">@font/estedad</item>
</style>

<style name="FontLexend">
     <item name="android:fontFamily">@font/lexend</item>
</style>

and in a base Activity.onCreate():

val fontFamily = EmbeddedFontFamily.from(sharedPreferencesRepository.getString(PrefKeys.FONT_FAMILY, "default"))
if (fontFamily !== EmbeddedFontFamily.DEFAULT) {
    getTheme().applyStyle(fontFamily.style, true)
}

This works everywhere except menu items.

For that I have to do this workaround after the menu is modified.

/**
 * Sets the correct typeface for everything in the drawer.
 *
 * The drawer library forces the `android:fontFamily` attribute, overriding the value in the
 * theme. Force-ably set the typeface for everything in the drawer if using a non-default font.
 */
private fun updateMainDrawerTypeface(fontFamily: EmbeddedFontFamily) {
    if (fontFamily == EmbeddedFontFamily.DEFAULT) return

    val typeface = ResourcesCompat.getFont(this, fontFamily.font) ?: return
    for (i in 0..binding.mainDrawer.adapter.itemCount) {
        val item = binding.mainDrawer.adapter.getItem(i)
        if (item !is Typefaceable) continue
        item.typeface = typeface
    }
}

(EmbeddedFontFamily is an enum with properties for the font resource and style resource).

Since the code only seems to use sans-serif and sans-serif-medium I think you might get the effect you want by (untested):

  1. Removing android:fontFamily="sans-serif" everywhere.
  2. Replacing android:fontFamily="sans-serif-medium" with android:textFontWeight="500", as "500" is the "medium" font weight.

Details

  •  Used library version: 9.0.2

Checklist

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions