Android and setting width and height programmatically in dp units

SK9 picture SK9 · Mar 10, 2011 · Viewed 193.5k times · Source

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"?

Answer

Robby Pond picture Robby Pond · Mar 10, 2011

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);