When should the dimens.xml file be used in Android?

rfgamaral picture rfgamaral · Sep 22, 2011 · Viewed 17.6k times · Source

For instance, in a specific layout I have the following XML:

<GridView
    android:id="@+id/gridView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="3dp"
    android:columnWidth="48dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="spacingWidth" />

This grid view is specific to this layout and I don't think I'll be using any other grid views with similar properties. That to say that the dimension values in the code are specific to that grid view.

Should I still move them to a dimens.xml file or it's fine to just leave them like that? If so, should I place values in the dimens.xml file only when that value is used across multiple layouts?

Answer

devunwired picture devunwired · Sep 22, 2011

I drop dimension values into a dimens.xml resource typically for three reasons:

  1. Reuse: I need multiple widgets or layouts to use the same value and I only want to change it once when updating or tweaking across the application.

  2. Density Difference: If I need the dimension to be slightly smaller or larger from ldpi -> hdpi or small -> large.

  3. Reading in from code: When I'm instantiating a view in the code and want to apply some static dimensions, putting them in dimens.xml as dp (or dip) allowing me to get a scaled value in Java code with Resources.getDimensionPixelSize().