Reputation: 33
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)
)
Upvotes: 3
Views: 3743
Reputation: 87844
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),
)
Upvotes: 4
Reputation: 3411
You need to rename your font to lower cases as per google recommendations.
Further you can set font using:
myTextView.typeface = ResourcesCompat.getFont(this, R.font.regular)
For more details refer to :
https://johncodeos.com/how-to-add-custom-fonts-in-your-android-app-using-kotlin/
Upvotes: 0
Reputation: 219
replace line with this
typeface = Typeface.createFromAsset(getAssets(),"font/Regular.otf")
Happy Coding!
Upvotes: 0