How to use dimens.xml
-
Create a new
dimens.xmlfile by right clicking thevaluesfolder and choosing New > Values resource file. Writedimensfor the name. (You could also call itdimenordimensions. The name doesn’t really matter, only thedimenresource type that it will include.) -
Add a
dimenname and value.<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="my_value">16dp</dimen> </resources>Values can be in
dp,px, orsp. -
Use the value in xml
<TextView android:padding="@dimen/my_value" ... />or in code
float sizeInPixels = getResources().getDimension(R.dimen.my_value);
When to use dimens.xml
Thanks to this answer for more ideas.
-
Reusing values – If you need to use the same dimension multiple places throughout your app (for example, Activity layout padding or a TextView
textSize), then using a singledimenvalue will make it much easier to adjust later. This is the same idea as using styles and themes. -
Supporting Multiple Screens – A padding of
8dpmight look fine on a phone but terrible on a 10″ tablet. You can create multipledimens.xmlto be used with different screens. That way you could do something like set8dpfor the phone and64dpfor the tablet. To create anotherdimens.xmlfile, right click yourresfolder and choose New > Value resource file. (see this answer for details) -
Convenient
dptopxcode conversion – In code you usually need to work with pixel values. However you still have to think about the device density and the conversion is annoying to do programmatically. If you have a constantdpvalue, you can get it in pixels easy like this forfloat:float sizeInPixels = getResources().getDimension(R.dimen.my_value);or this for
int:int sizeInPixels = getResources().getDimensionPixelSize(R.dimen.my_value);
I give many more details of how to do these things in my fuller answer.
When not to use dimens.xml
-
Don’t put your values in
dimens.xmlif it is going to make them more difficult to maintain. Generally that will be whenever it doesn’t fall into the categories I listed above. Usingdimens.xmlmakes the code harder to read because you have to flip back and forth between two files to see what the actual values are. It’s not worth it (in my opinion) for individual Views. -
Strings are different. All strings should go in a resource file like
strings.xmlbecause almost all strings need to be translated when internationalizing your app. Most dimension values, on the other hand, do not need to change for a different locality. Android Studio seems to support this reasoning. Defining a string directly in the layout xml will give a warning but defining adpvalue won’t.