Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"...

like image 539
Héctor Júdez Sapena Avatar asked Jun 20 '12 13:06

Héctor Júdez Sapena


People also ask

What is the content of dimens XML?

dimens. xml is used for defining the dimensions for different widgets to be included in the Android project.


2 Answers

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

like image 87
AndroidGecko Avatar answered Oct 26 '22 23:10

AndroidGecko


Context.getResources().getDimension(int id); 
like image 44
Jug6ernaut Avatar answered Oct 27 '22 00:10

Jug6ernaut