Load dimension value from res/values/dimension.xml from source code

Héctor Júdez Sapena picture Héctor Júdez Sapena · Jun 20, 2012 · Viewed 204.9k times · Source

I'd like to load the value as it is. I have two dimension.xml files, one in /res/values/dimension.xml and the other one in /res/values-sw360dp/dimension.xml.

From source code I'd like to do something like

getResources().getDimension(R.dimen.tutorial_cross_marginTop);

This works but the value I get is multiplied times the screen density factor (1.5 for hdpi, 2.0 for xhdpi, etc).

I also tried to do

getResources().getString(R.dimen.tutorial_cross_marginTop);

This would work in principle but I get a string that ends in "dip"...

Answer

AndroidGecko picture AndroidGecko · Apr 29, 2013

In my dimens.xml I have

<dimen name="test">48dp</dimen>

In code If I do

int valueInPixels = (int) getResources().getDimension(R.dimen.test)

this will return 72 which as docs state is multiplied by density of current phone (48dp x 1.5 in my case)

exactly as docs state :

Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current DisplayMetrics associated with the resources.

so if you want exact dp value just as in xml just divide it with DisplayMetrics density

int dp = (int) (getResources().getDimension(R.dimen.test) / getResources().getDisplayMetrics().density)

dp will be 48 now