Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define text as h1 in jetpack compose?

In Type.kt Typography I defined h1 TextStyle like this:

h1 = TextStyle(
     fontFamily = FontFamily.SansSerif,
     fontWeight = FontWeight.W500,
     fontSize = 70.sp,
     color = Color(0xFFF8F9FC)
),

Now how can I define the Text widget to be an h1 so these TextStyles applies automatically?

like image 979
Saif Essam Avatar asked Oct 26 '25 03:10

Saif Essam


2 Answers

You can get the current theme h1 from any @Composable with MaterialTheme.typography.h1, so your widget might look like this:

@Composable
fun TextH1(
    text: String,
    modifier: Modifier = Modifier,
) {
    Text(
        text = text,
        modifier = modifier,
        style = MaterialTheme.typography.h1,
    )
}
like image 73
Philip Dukhov Avatar answered Oct 28 '25 15:10

Philip Dukhov


If you plan on using your style globally for all text that you want identified as h1, you should create a custom composable for that and apply your style there:

@Composable
fun TextH1(
   text: String,
   modifier: Modifier = Modifier
) {
   Text(text = text, modifier = modifier, textStyle = h1)
}

Alternatively, you could use CompositionLocal, but that tends to become cumbersome if used extensively.

like image 45
Johann Avatar answered Oct 28 '25 17:10

Johann