D
D
Dmitry Kinash2015-01-09 15:48:49
Android
Dmitry Kinash, 2015-01-09 15:48:49

Why does getDimension() return 1.5 times the value specified in dimens.xml?

I have a dimens.xml resource file with content like this (for testing purposes):

<resources>
    <dimen name="tab_padding">16dp</dimen>
    <dimen name="title_text_size">20sp</dimen>
    <dimen name="row_text_size">17sp</dimen>
</resources>

With the use directly in the layout xml file, everything is fine, but there are problems with programmatic layout with expressions of the form:
txtView.setTextSize(getResources().getDimension(R.dimen.row_text_size));

Debugging showed that the problem is in the getDimension() function , which increases all dimensions by 1.5 times . In the Expressions scoreboard, I got the following results (compare with the original values ​​in the resource file):
getResources().getDimension(R.dimen.tab_padding) = 24
getResources().getDimension(R.dimen.title_text_size) = 30
getResources().getDimension (R.dimen.row_text_size) = 25.5

So what's the problem? Has anyone heard of something like this?
PS I had a hypothesis that android recalculates sp into dp so crookedly. As you can see from the file, I already started experimenting with units, but the explicit introduction of dp did not clarify anything either :(
Solution! Thanks to a tip from one pavelI realized that the recalculation takes place in the unit px. Those. in my case it is enough to do:
txtView.setTextSize(
      TypedValue.COMPLEX_UNIT_PX, 
      getResources().getDimension(R.dimen.row_text_size));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
one pavel, 2015-01-09
@Dementor

The documentation clearly says
developer.android.com/reference/android/content/re...
and if you google the first two links
stackoverflow.com/questions/6784353/inconsistency-...
stackoverflow.com/questions/14540293/get-dimension...
and if you open the source of the method, you can see how it turns out the return is pure
. To be good, it was invented to create values ​​for different types of screens
https://developer.android.com/samples/MediaRouter/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question