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,
)
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.
private val myCustomFont = FontFamily(
Font(R.font.helvetica_nue),
)
val Typography = Typography(
defaultFontFamily = myCustomFont,
)
@Composable
fun MyApplicationTheme(content: @Composable () -> Unit) {
MaterialTheme(
typography = Typography,
)
}
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:
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
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 eg
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.