How to change font family in Jetpack Compose programmatically?

Viewed 554

I'm building an Android app and I wanted to add an option in the settings for the user to choose either he wants to use The app custom font family or just use the dafault system font family and maybe also options for other fonts. Is there an option in compose to do this?

1 Answers

I was able to do it by using the defaultFontFamily parameter, adding an extra parameter to MyAppTheme Composable and passing the typography object to the MaterialTheme() constructor instead of the default one as you can see the code below :

fun getTypography(fontFamily: FontFamily) = Typography(
    defaultFontFamily = fontFamily
)

In Theme.kt :

@Composable
fun MyAppTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    // Added fontFamily param
    fontFamily: FontFamily = Rubik,
    content: @Composable () -> Unit) {

    val colors = if (darkTheme) {
        DarkColorPalette
    } else {
        LightColorPalette
    }

    val typography = getTypography(fontFamily)

    MaterialTheme(
        colors = colors,
        typography = typography,
        shapes = Shapes,
        content = content
    )
}

Related