Targeting Multiple Densities in Android

42 sec read

One of the main reasons of Android OS popularity is its ablity to run and support a wide array of device (Mobiles, Tablets, Wearables, TV).

So, for example a UX that works perfectly for one type of devices having same screen densities might not work effectivly for other devices having differnt screen densities. To a great extent this can be handled in android application from a developer point of view.

public int getDisplayMetricsFactorForDevice() {
DisplayMetrics metrics = null;
metrics = new DisplayMetrics();
Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (metrics.density >= 4.0){
return 3;
} else if (metrics.density >= 3.0 && metrics.density < 4.0){ return 2; } else if (metrics.density >= 2.0 && metrics.density < 3.0){ return 1; }else if (metrics.density >= 1.5 && metrics.density < 2.0){ return 1; } else if (metrics.density >= 1.0 && metrics.density < 1.5){ return 1; } return 0; }

above method returns a differnt device density factor for different dentsity Device. During application runtime this method can be used to get device density factor. Device density factor can be used later on to form actual width / height of your Custom UI component.

Happy Coding !

Note : Dear Copy-Paste Community :).
Hope you are doing good.
If you are a software engineer study the material before copy pasting.

Else knowledge gets increased when it is shared.