Android and setting width and height programmatically in dp units


I'm doing:

button.setLayoutParams(new GridView.LayoutParams(65, 65));

According to the docs the units for the width and height (both 65 in the above) are "pixels". How do you force this to be device independent pixels, or "dp"?

3/10/2011 3:38:51 AM

Accepted Answer

You'll have to convert it from dps to pixels using the display scale factor.

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);
3/10/2011 12:58:55 PM

I know this is an old question however I've found a much neater way of doing this conversion.

TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65, getResources().getDisplayMetrics());

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow