When accessing the textSize of a textView I do not get same value that I put in there before.
Hello,
I'm new to Kotlin and Stackoverflow.
In a Kotlin app I would like to dimension the size of buttons and textViews depending on the width of the display. So I set the textSize (and others) programmatically. In doing so, I stumbled upon a problem, that I do not understand:
tdp20.textSize = size20before
var size20after = tdp20.textSize
where tdp20 is some textView and size20before is some value (that I got from var size20=tdp20.textSize)
I was surprised to find, that size20before and size20after are NOT equal. Depending on the gsm that I use the values differ by a factor of 1.5 (an old Moto C with Android 7) and 4.0 (realme 8 with Android 12)
I would be very grateful for an explanation.
Kind regards
This is due to a weird (and frankly poor) design decision in the TextView class.
You set the text size using SP units, but you get the size back in pixel units.
Here's the documentation for getting text size:
returns the size (in pixels) of the default text size in this TextView.
And here's the documentation for setting text size:
Set the default text size to the given value, interpreted as "scaled pixel" units. This size is adjusted based on the current density and user font size preference.