How to use dimens.xml
- Create a new
dimens.xml
file by right clicking thevalues
folder and choosing New > Values resource file. Writedimens
for the name. (You could also call itdimen
ordimensions
. The name doesn't really matter, only thedimen
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.