Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack

How do i apply a default font to all Text() elements in the app using Jetpack Compose?


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,
        )

Solution

  • 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

    enter image description here

    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: