How to refer xml style from Jetpack Compose Modifier?

Viewed 3304

How do I reference a resource style from Compose widget?

styles.xml

<style name="Style.Monet.TextView.HeaderSubtext" parent="Widget.AppCompat.TextView">
    <item name="android:textColor">#737373</item>
    <item name="android:textSize">12sp</item>
    <item name="android:layout_marginStart">16dp</item>
    <item name="android:layout_marginBottom">16dp</item>
    <item name="android:layout_marginEnd">24dp</item>
</style>

MyComponent.kt

Text(text = "June 2021", style = TextStyle(R.style.Style_TextView_HeaderSubtext))

But this doesn't work. Is there a way to make this work?

1 Answers

You can't do that, because Compose Text is styled differently, and TextStyle it not responsible so all xml style is responsible. As an example, you cannot add margins.

You can create compose TextStyle:

val textStyle = TextStyle(
    color = Color(0xFF737373),
    fontSize = 12.sp,
)

And use it globally in your project or pass to your theme. This is a preferred way to use styles in compose, check out more about it in the theming documentation. Customize one of material available styles:

val typography = Typography(
        body1 = TextStyle(
                color = Color(0xFF737373),
                fontSize = 12.sp,
        )
)

Pass it to your theme:

@Composable
fun ComposePlaygroundTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit
) {
    val colors = if (darkTheme) {
        DarkThemeColors
    } else {
        LightThemeColors
    }
    MaterialTheme(
        colors = colors,
        typography = typography,
        shapes = shapes,
        content = content,
    )
}

Apply Theme at the composable root:

setContent {
    ComposePlaygroundTheme {
        // your composables
    }
}

After that you can use it like this:

Text("",
    style = MaterialTheme.typography.body1,
)

To apply margins in compose you need to use padding modifier. Check out more about layout in compose in the layout documentation:

If you wanna reuse same styled text in compose, you can create your own composable with predefined style and padding:

@Composable
fun ProjectText(text: String, modifier: Modifier) {
// without material theme you can just define text style here and pass to text
//    val textStyle = TextStyle(
//        color = Color(0xFF737373),
//        fontSize = 12.sp,
    )
    Text("",
        style = MaterialTheme.typography.body1,
        modifier = modifier
            .padding(start = 16.dp, end = 24.dp, bottom = 16.dp)
    )
}

Usage:

ProjectText("June 2021")
Related