Monday, August 22, 2011

Android programmatic density independent pixels

I've been doing a bunch of Android programming lately, working on porting the iBridalGown iOS app to Android, so I've been using a lot of "dip" (density independent pixels) measuring in my layouts. For example, in a TextView, I might specify something like this in XML:

<TextView
      android:id="@+id/headertext"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:minHeight="48dip"
      android:textSize="24dip"
      android:text="My Dresses"
/>

But what if, within the Activity code, I want to change one of these measurements? There are no Java methods in the Android SDK that accept density independent pixels!

Well, here's how. Just multiply the size in pixels by a scale factor defined in the context's resources, like so:

float scale = context.getResources().getDisplayMetrics().density;
float size = sizeInPixels * scale;

And there's that. I hope it helps :) Please join the conversation with a comment.

2 comments:

  1. thanks for sharing up such a nice and helpful information.

    ReplyDelete
  2. Thanks for inspirational information you have shared with us through this post. It is really productive, informative and useful. The efforts are highly appreciative you made here to sharing this wonderful post. Hope that you will come with more useful articles in future. Thanks for prolific sharing.

    ReplyDelete