How to use otf type font file in Android Compose?

Viewed 1167

I'm learning to use Android Jetpack Compose. Now I have a Regular.otf font file in assets/font. I want to use it in Text.

java.lang.RuntimeException: Font asset not found /commonui/src/main/assets/font/Regular.otf
    at android.graphics.Typeface.createFromFile(Typeface.java:998)
    at android.graphics.Typeface.createFromFile(Typeface.java:1012)

I tried some methods but none of them solved.

    val fontFamily = FontFamily(
        typeface = Typeface.createFromFile("commonui/src/main/assets/font/Regular.otf")
    )
    Text(
        text = "Font",
        style = TextStyle(fontFamily = fontFamily)
    )
3 Answers

You should put the font resource in the res/font/ folder and name it in lowercase, for example regular.otf. It is also probably a good idea to give it a real font name rather than a font style name. Read more about adding font resources in documentation.

You can then use ResourcesCompat inside composable, providing the context from LocalContext.

To avoid unnecessary calculations, you should at least put it inside remember, but ideally move it to your theme. Check out more about Theming in Compose

val context = LocalContext.current
val fontFamily = remember {
    FontFamily(
        typeface = ResourcesCompat.getFont(context, R.font.regular)!!
    )
}
Text(
    "Hello",
    style = TextStyle(fontFamily = fontFamily),
)

replace line with this

typeface = Typeface.createFromAsset(getAssets(),"font/Regular.otf")

Happy Coding!

Related