Skip to content

Use DIP, SP metrics programmatically

Tuesday, 4 October, 2011

Hi guys!

Today I had this problem where I needed to create some TextViews inside a TableRow, but I needed to specify its setMinWidth with some value in the SP metrics, like you do at the XML file:¬†setWidth=”100sp”. The problem is that setMinWidth or setWidth are called giving a number in pixels. So I searched a little bit and found this simple solution.

The goal is to calculate the number of pixels according to a given value in the SP metrics. Converting 20sp into pixels is done by doing

TextView tv0 = new TextView(this);
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
tv0.setMinimumWidth(px);

And that’s it!
If you want it with the DIP metrics, you just need to change the TypedValue from TypedValue.COMPLEX_UNIT_SP to TypedValue.COMPLEX_UNIT_DIP or whatever other metric you want to use.

Hope it was helpful.

About these ads

From → Uncategorized

Leave a Comment

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: