4

I'm using the following code :

ImageView i = new ImageView(mContext);

i.setImageResource(mImageIds[position]);

i.setScaleType(ImageView.ScaleType.FIT_XY);

       //pixels settings !!!

i.setLayoutParams(new Gallery.LayoutParams(200, 100));

but as you can see, it is setting the layout dimensions in pixels.

Does anybody know how to do the same thing but in "dip" ?

Community
  • 1
  • 1
Fabien
  • 1,967
  • 8
  • 30
  • 42

3 Answers3

19

The following helper method takes as input device independent pixels (DIP) and returns actual pixels for the current device.

private int getPixels(int dipValue) {
    Resources r = getResources();
    int px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                                            dipValue, 
                                            r.getDisplayMetrics());
    return px;
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
devanshu_kaushik
  • 929
  • 11
  • 30
10

If you store your dimension as a resource, you can use

getResources().getDimensionPixelSize(id);

This will also make it easier to adjust your layouts.

ndw
  • 513
  • 6
  • 14
1

See http://developer.android.com/guide/practices/screens_support.html#screen-independence

On how to convert from dpi to pixels.

Cpt.Ohlund
  • 2,589
  • 1
  • 20
  • 15
  • thanks its look interesting to me but I dont understand the formula... Do you understand it ? can you give me an example on how to convert 100dip to pixel for example ? – Fabien Aug 26 '10 at 14:41
  • I found this solution that work perfectly : http://stackoverflow.com/questions/2238883/what-is-the-correct-way-to-specify-dimensions-in-dip-from-java-code – Fabien Aug 26 '10 at 14:57