I need to apply a common font to all the Text() used in my entire app. Currently i am applying it manually to each text using a style or font as follows. How can i specify this as a global theme for the app? In normal xml layouts, i was using a custom TextView widget to achieve this.
Text(
text = stringResource(id = R.string.userName),
style = typography.h2,
fontSize = 20.sp,
)
CodePudding user response:
Jetpack Compose supports theming and a uniform font can be applied by specifying a custom font in app theme. Steps to do this are as follows.
Copy your custom font to res/font directory ex: helvetica_nue.ttf
Create a Kotlin file (Type.kt) and add your Font family object here. Specify the defaultFontFamily as your custom font. If you wish to perform some additional customization you may add your styles to body1 typography, as this is the default typography used for all Text() unless specified.
private val myCustomFont = FontFamily(
Font(R.font.helvetica_nue),
)
val Typography = Typography(
defaultFontFamily = myCustomFont,
)
Create a Kotiln file (Theme.kt or any name) and declare you app theme
@Composable
fun MyApplicationTheme(content: @Composable () -> Unit) {
MaterialTheme(
typography = Typography,
)
}
In your activity/fragment, wrap your apps main Composable within this theme
MyApplicationTheme {
NewsDetailScreen()
}
Now your app will display text in the specified font wherever the theme is applied.
Reference: https://developer.android.com/jetpack/compose/themes/material#typography
If you want to use the same typeface throughout, specify the defaultFontFamily parameter and omit the fontFamily of any TextStyle elements:
CodePudding user response:
An option is to define a custom composable, something like:
@Composable
fun H2Text(
text: AnnotatedString,
modifier: Modifier = Modifier) {
Text(
text = text,
modifier = modifier,
style = typography.h2,
fontSize = 20.sp,
)
}
and then use in the app H2Text
instead of Text
CodePudding user response:
One similar approach would be to first create custom implementation over Text composable, lets call it CustomText. Then for your use case, you can write wrappers over most used text styles, for eg
@Composable
TextH2(text : String) {
//call your own wrapper over framework Text composable
CustomText(text = text, typography = h2)
}
To make things simpler you can wrap font resource, weight and size together and then create specific implementation of this class for e.g
val h2 = CustomTypography(font = R.font.your-ttf-file, fontSize = 20.sp, fontWeight = Medium)
Above styling data is handled inside one single composable, which in our case is CustomText.