如何在 Jetpack Compose 中为每个区域设置特定的字体系列

how to set specific font family for each locale in jetpack compose

在 Jetpack Compose 中,您可以通过编辑 type 文件来设置您的特定字体:

val MyFont= FontFamily(
    Font(R.font.myfont, FontWeight.Normal)
)

// Set of Material typography styles to start with
val Typography = Typography(
    body1 = TextStyle(
        fontFamily = MyFont,
        fontWeight = FontWeight.Normal,
        fontSize = 16.sp
    ),
    button = TextStyle(
        fontFamily = MyFont,
        fontWeight = FontWeight.SemiBold,
        fontSize = 14.sp
    ),
    defaultFontFamily = MyFont
)

但我的问题是我有多个区域设置,我想为每个区域设置特定的字体。

在使用 Compose 之前,我的方法是用每种语言 values folder 创建一个 style.xml 文件,然后以更改字体系列的方式编辑 style.xml。但是这种方法在使用 Compose 时不起作用。

那么我怎样才能为每个语言环境设置不同的字体系列呢?

不确定是否有更好的方法,但我认为可以使用简单的策略模式来实现它。
fontFamily 创建接口,即

interface MyFont {
    fun getBody1FontFamily()
    fun getButtonFontFamily()
}

然后实施它,即

class EnglishFont: MyFont {
   fun getBody1FontFamily() = // font for body1 on English locale
   fun getButtonFontFamily() = // font for button on English locale
}

class KoreanFont: MyFont {
   fun getBody1FontFamily() = // font for body1 on Korean locale
   fun getButtonFontFamily() = // font for button on Korean locale
}

然后,在您的可组合函数中,您可以根据语言环境创建 myFont 对象并将该对象注入 Typography

val Typography = Typography(
    body1 = TextStyle(
        fontFamily = myFont.getBody1FontFamily(),
        fontWeight = FontWeight.Normal,
        fontSize = 16.sp
    ),
    button = TextStyle(
        fontFamily = myFont.getButtonFontFamily(),
        fontWeight = FontWeight.SemiBold,
        fontSize = 14.sp
    ),
    defaultFontFamily = MyFont
)

如果你想实现这一点,你需要按照以下步骤操作:

  1. 这些字体应该同名,放在不同的字体locale文件夹中。

  2. 使用该字体名称定义 FontFamily

    val myFontFamily = FontFamily(
        Font(R.font.lato_light, FontWeight.Light),
        Font(R.font.lato_regular, FontWeight.Normal),
        Font(R.font.lato_italic, FontWeight.Normal, FontStyle.Italic),
        Font(R.font.lato_regular, FontWeight.Medium),
        Font(R.font.lato_bold, FontWeight.Bold)
    )
    
  3. 在你的Text

    中使用
    val text = "Hello Android Developers"
    Column(Modifier.fillMaxWidth().padding(16.dp)) {
        Text(text, fontFamily = myFontFamily, fontWeight = FontWeight.Light)
        Text(text, fontFamily = myFontFamily, fontWeight = FontWeight.Medium)
        Text(text, fontFamily = myFontFamily, fontStyle = FontStyle.Italic)
    }
    

英语和西班牙语语言环境的结果如下: