Skip to content

Instantly share code, notes, and snippets.

@Tarubali
Last active February 23, 2020 06:44
Show Gist options
  • Save Tarubali/7ebe4819a3337aba707e to your computer and use it in GitHub Desktop.
Save Tarubali/7ebe4819a3337aba707e to your computer and use it in GitHub Desktop.
A simple java class to find out the independent pixel resolution of Android device
public class ScreenUtility {
private Activity activity;
private float dpWidth;
private float dpHeight;
public ScreenUtility(Activity activity) {
this.activity = activity;
Display display = activity.getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float density = activity.getResources().getDisplayMetrics.density;
dpHeight = outMetrics.heighPixels / density;
dpWidth = outMetrics.widthPixels / density;
}
public float getWidth() { return dpWidth; }
public float getHeight() { return dpHeight; }
}
//USAGE
//Declare an instance of the ScreenUtility class in your activity onCreate
//like
//ScreenUtility utility = new ScreenUtility(this);
//then
//utility.getWidth() and utility.getHeight() will return the appropriate values
//output
//using Log to console or Toast to screen
@AnderWeb
Copy link

Why not context.getResources().getDisplaymetrics()?
Better than having to use an activity, it would work from any context.

@Tarubali
Copy link
Author

I found this in a lynda tutorial and it works. It can be used without the class or as a static class or as you mentioned. I got tired of saving code in evernote so I posted it here :)

@ec84b4
Copy link

ec84b4 commented Dec 5, 2014

this doesn't include bottom navigation height and also changes on orientation change.
i've written something similar but it includes the device navigation buttons height and doesn't change on different orientation/

https://gist.github.com/hister/4a2e25fba3cdf657ff08

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment