31 Jul 2015

Does setWidth(int pixels) use dip or px?

Does setWidth(int pixels) use device independent pixel or physical pixel as unit? For example, does setWidth(100) set the a view's width to 100 dips or 100 pxs?

It uses pixels, but I'm sure you're wondering how to use dips instead. The answer is in TypedValue.applyDimension(). Here's an example of how to convert dips to px in code:
// Converts 16 dip into its equivalent px
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, r.getDisplayMetrics());

You can also call nbDips * getResources().getDisplayMetrics().density







26 Jun 2015

How to get the screen density programmatically in android?

How to find the screen dpi of the current device?

You can get info on the display from the DisplayMetrics struct:
DisplayMetrics metrics = getResources().getDisplayMetrics();
getResources().getDisplayMetrics().density;
Though Android doesn't use a direct pixel mapping, it uses a handful of quantized Density Independent Pixel values then scales to the actual screen size. So the metrics.densityDpi property will be one of the DENSITY_??? constants (120, 160, 213, 240, 320, 480 or 640 dpi).
If you need the actual lcd pixel density (perhaps for an OpenGL app) you can get it from the metrics.xdpi and metrics.ydpi properties for horizontal and vertical density respectively.
If you are targeting API Levels earlier than 4. The metrics.density property is a floating point scaling factor from the reference density (160dpi). The same value now provided by metrics.densityDpican be calculated
int densityDpi = (int)(metrics.density * 160f);
Here,

0.75 - ldpi
1.0 - mdpi
1.5 - hdpi
2.0 - xhdpi
3.0 - xxhdpi
4.0 - xxxhdpi


Or,
Use follwing code,

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch(metrics.densityDpi){
     case DisplayMetrics.DENSITY_LOW:
                break;
     case DisplayMetrics.DENSITY_MEDIUM:
                 break;
     case DisplayMetrics.DENSITY_HIGH:
                 break;
}
This will work in API lavel 4 or higher.

More details about px, dip, dp and sp units in Android

1) px = dp * ( dpi / 160 )
2) px is one pixel.
3) sp is scale-independent pixels.
4) sp for font sizes
5) dip is Density-independent pixels.
6) dip for everything else, where dip == dp
7) 100*100 px image for mdpi
8) 150*150 px image for hdpi
9) 200*200 px image for xhdpi
10) 1080x1920    save it in “drawable-xxhdpi” folder
11) 480x800      save it in “drawable-hdpi” folder
12) 320x480      save it in “drawable-mdpi” folder
13) 1280x720     save it in “drawable-xhdpi” folder
14) If running on mdpi device, 150x150 px image will take up 150*150 dp of screen space.
15) If running on hdpi device, 150x150 px image will take up 100*100 dp of screen space.
16) If running on xhdpi device, 150x150 px image will take up 75*75 dp of screen space.