Friday 16 June 2017

How to get Resolution of android device during runtime

How to get Resolution of android device during runtime


Getting Resolution of the android screen is one of the important aspect when application is to be made for different resolution devices.
So, in order to get the resolution of the device there is predefined library(Display Metrics) in android sdk. You just need to call the method provided by it. The methods are mentioned below.

 DisplayMetrics DM = new DisplayMetrics();  
 getWindowManager().getDefaultDisplay().getMetrics(DM);  

This DM object have the information about no. of pixels in height and width and density of the screen. To get these information Call following method:-

For no. of pixels in length

 DM.heightPixels;  

For no. of pixels in width

 DM.widthPixels;  

For Density of Screen

 DM.densityDpi;  

This information is used frequently in code so it is better to make a wrapper class of this and add some basic functions in it. The custom Wrapper class is defined below.

Wrapper Class for DM object


Firstly you have to pass the DM object to this class's constructor.

 DisplayMetrics DM = new DisplayMetrics();  
 getWindowManager().getDefaultDisplay().getMetrics(DM);  
 ScreenResolution SR = new ScreenResolution(DM);  

Now create the custom class named as ScreenResolution:-

import android.util.DisplayMetrics;
public class ScreenResolution { public static DisplayMetrics dm; public ScreenResolution(DisplayMetrics dm){ this.dm=dm; } public static int getHeight(){ return dm.heightPixels; } public static int getWidth(){ return dm.widthPixels; } public static int getDensity(){ return dm.densityDpi; } public static int percent_of_width(int param){ return ((param*(dm.widthPixels))/100); } public static int percent_of_height(int param){ return ((param*(dm.heightPixels))/100); } }

This class should be placed in custom Package. This class is beneficial in storing and getting the information about the screen's resolution.

ENJOY  DEVELOPING!!

No comments:

Post a Comment