Home > OS >  How to define text as h1 in jetpack compose?
How to define text as h1 in jetpack compose?

Time:10-29

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?

CodePudding user response:

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,
   modififer: Modifier = Modifier
) {
   Text(text = text, modifier = modifier, textStyle = h1)
}

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

CodePudding user response:

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,
    )
}
  • Related