简体   繁体   English

如何以编程方式更改 Jetpack Compose 中的字体系列?

[英]How to change font family in Jetpack Compose programmatically?

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.我正在构建一个 Android 应用程序,我想在设置中添加一个选项,供用户选择他想要使用应用程序自定义字体系列,或者只使用默认系统字体系列,也许还有其他字体的选项。 Is there an option in compose to do this? compose 中有一个选项可以执行此操作吗?

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 :我可以通过使用defaultFontFamily参数来做到这一点,向MyAppTheme Composable 添加一个额外的参数并将版式对象传递给MaterialTheme()构造函数而不是默认的构造函数,如下面的代码所示:

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

In Theme.kt :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
    )
}

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

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