Compose: Inherit TextStyle from another TextStyle

Viewed 352

In my app, I have some Styles which inherit from another Style like this one:

styles.xml

<style name="RegularM">
    <item name="android:textSize">18sp</item>
    <item name="android:fontFamily">@font/regular</item>
</style>

<style name="ListRow" parent="RegularM">
    <item name="android:textColor">@color/black</item>
</style>

This makes a ListRow entry a black-colored text with 18sp and uses a regular font.

So, now I convert this one to compose.

Fonts.kt

val Regular = FontFamily(
     Font(R.font.regular),
)

val RegularM = TextStyle(
     fontFamily = Regular,
     fontSize = 18.sp
)

So far, so good.

Now I want to create the ListRow TextStyle:

val ListRow = TextStyle(
    color = Black,
    ? inherit from RegularM
)

But I can't inherit from RegularM. I have to retype each property for the ListRow TextStyle. But this seem's to be wrong.

How I can inherit from the RegularM, or is using TextStyle for this one the wrong way?

2 Answers

TextStyle is not a data class, but still has copy(...) method implemented which you can use exactly for this issue:

var ListRow = RegularM.copy(color = Black)

With the TestStyle you can use the copy method as suggested by @Philip but you can also use the merge method.

Example:

Text(text = "This is my text",
    style = ( 
      RegularM.merge(TextStyle(color = Black))
    )
)
Related