0

Is it possible to read a TextAppearance attribute programmatically?

I have this TextAppearance style:

<style name="TextAppearance.DesignSystem.Payback.Headline3" parent="@style/TextAppearance.MaterialComponents.Headline3">
    <item name="android:fontFamily">@font/payback</item>
    <item name="android:letterSpacing">0.0</item>
    <item name="android:textColor">?android:attr/textColorPrimary</item>
    <item name="android:textSize">40sp</item>
    <item name="android:textStyle">normal</item>
    <item name="fontFamily">@font/payback</item>
</style>

And I would like to read the android:textSize programmatically.

I managed to get it like this:

private val textAppearanceTextView by lazy { TextView(context) }

fun getTextAppearanceTextSize(@StyleRes textAppearance: Int): Int {
    textAppearanceTextView.apply {
        setTextAppearance(textAppearance)
        return textSize.roundToInt()
    }
}

but this is pretty ugly.

Is there a cleaner way to read an attribute of a TextAppearance?

Mattia Righetti
  • 1,265
  • 1
  • 18
  • 31
Roberto Leinardi
  • 10,641
  • 6
  • 65
  • 69
  • 1
    `textAppearanceTextView.textSize` will return you the TextSize in Pixels . u can not get cleaner than that . Do you want to get text Size from Style or From View ? – ADM Apr 13 '21 at 08:42
  • I would like to read the textSize of the style, without the need to create a useless `TextView` just to apply to it the `TextAppearance` and then read the size. – Roberto Leinardi Apr 13 '21 at 09:11

0 Answers0