Android: Using metric units from within code

When designing a layout in XML, Android supports a number of different metrics. From your Java code though, methods like setPadding or setTextSize only take absolute pixel values. It took me a while to find a solution, but apparently the (slightly too cumbersome, I feel) way to to this is through defining a Dimension Resource.

For example, create a resource file in ./res/values/dimens.xml and add this item:

<dimen name=table_padding>10dp</dimen>

Then, from within your activity you would do:

int tablePadding = getResources().getDimensionPixelSize(R.dimen.table_padding);

I wonder whether the conversion code used by getDimension/getDimensionPixelSize is exposed somewhere.

Edit April 2010: There’s actually a snippet in this document about screen sizes, which is essentially this function:

private int dipToPixels(float dipValue) {
     return (int) (dipValue * getResources().getDisplayMetrics().density + 0.5f);

As far as I can tell, the +0.5 part is intended to ensure that the result is at least 1 pixel always.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s