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

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


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 conversionsare 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


Context.getResources().getDimension(int id);


The Resource class also has a method getDimensionPixelSize() which I think will fit your needs.