2017年3月10日 星期五

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