android Imageview layoutparams in dip?

Fabien picture Fabien · Aug 26, 2010 · Viewed 15.5k times · Source

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

Answer

devanshu_kaushik picture devanshu_kaushik · Dec 1, 2011

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