Define dimensions

Download android eBook

Example

Dimensions are typically stored in a resource file names dimens.xml. They are defined using a <dimen> element.

res/values/dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="small_padding">5dp</dimen>
    <dimen name="medium_padding">10dp</dimen>
    <dimen name="large_padding">20dp</dimen>

    <dimen name="small_font">14sp</dimen>
    <dimen name="medium_font">16sp</dimen>
    <dimen name="large_font">20sp</dimen>
</resources> 

You can use different units :

  • sp : Scale-independent Pixels. For fonts.
  • dp : Density-independent Pixels. For everything else.
  • pt : Points
  • px : Pixels
  • mm : Millimeters
  • im : Inches

Dimensions can now be referenced in XML with the syntax @dimen/name_of_the_dimension.

For example:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/large_padding">
</RelativeLayout>

Stats

Contributors: 2
2016-01-15
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook