Search code examples
androidlocaleandroid-jetpack-composefont-family

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


In Jetpack Compose, you can set your specific font by editing the type file:

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
)

But my problem is that I have multiple locales, and I want to set the specific font for each one.

Before using Compose, my approach was to create a style.xml file in each language values folder and edit the style.xml in a way that changes the font family. but this approach won't work when using Compose.

So how can I have a different font family for each locale?


Solution

  • If you want to achieve this you need to follow some steps as below:

    1. These fonts should be the same name and put in the different font locale folder. Put fonts in different folder

    2. Define FontFamily with that font name

      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. Use in your 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)
      }
      

    The result of English and Spanish locale as below: Text will be in different font in different locales (en&es)