7

The method

public void setPadding (int left, int top, int right, int bottom)

someview.setPadding(1,1,1,1);

this will give padding with 1px in each side. How can I give 1dip instead of 1px ?

the values fro left , top right and bottom are in pixels , how can I give values programatically in code in dip ?

Thanks

Lukap
  • 31,523
  • 64
  • 157
  • 244

3 Answers3

25

Use following code to get pixels from given value in dp.

Resources res = getResources();
float value = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDP, res.getDisplayMetrics());

where valueInDP is value in dp and this will return corresponding pixel value according to screen density.

or you can use following -

float value = valueInDP * getResources().getDisplayMetrics().density;
anujprashar
  • 6,263
  • 7
  • 52
  • 86
  • 1
    How would be the reverse ? from dip to px, is there any place where I can find more details – Lukap Oct 17 '11 at 12:44
  • Yes. check these links http://stackoverflow.com/questions/2406449/does-setwidthint-pixels-use-dip-or-px and http://stackoverflow.com/questions/2238883/what-is-the-correct-way-to-specify-dimensions-in-dip-from-java-code. – anujprashar Oct 17 '11 at 12:44
  • 1
    That value is in float, while the setPadding method requires integer parameters. – John61590 Nov 19 '15 at 10:03
  • Why is this method still in pixels? I thought it's not recommended for ages by now to use pixels instead of dp. The whole point of dp is that it looks the same on all screens. – Sarah Multitasker Mar 16 '23 at 14:25
3

What is the difference between "px", "dp", "dip" and "sp" on Android?

float scale = context.getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (your_dp_goes_here * scale + 0.5f);

view.setPadding(dpAsPixels , dpAsPixels , dpAsPixels , dpAsPixels );
view.setPaddingRelative(dpAsPixels , dpAsPixels , dpAsPixels , dpAsPixels );
Community
  • 1
  • 1
Pwnstar
  • 2,333
  • 2
  • 29
  • 52
0
getListView().setPadding(50,50,50,50);
Tim Flinn
  • 61
  • 1
  • 6