Using dimens.xml in Android

Suragch
4 min readJan 7, 2019

This is a repost of two answers I wrote on Stack Overflow (here and here).

How to use dimens.xml

  1. Create a new dimens.xml file by right clicking the values folder and choosing New > Values resource file. Write dimens for the name. (You could also call it dimen or dimensions. The name doesn't really matter, only the dimen resource type that it will include.)

2. Add a dimen name and value.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="my_value">16dp</dimen>
</resources>

Values can be in dp, px, or sp.

3. 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 post for more ideas.

1. 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 single dimen value will make it much easier to adjust later. This is the same idea as using styles and themes.

--

--