Last active
February 23, 2020 06:44
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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 :)
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/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not context.getResources().getDisplaymetrics()?
Better than having to use an activity, it would work from any context.