Skip to content

Instantly share code, notes, and snippets.

@fbongcam
Created February 9, 2022 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fbongcam/518d05afe1586942a2abebf96a2ff63b to your computer and use it in GitHub Desktop.
Save fbongcam/518d05afe1586942a2abebf96a2ff63b to your computer and use it in GitHub Desktop.
Collects useful data of the device physical screen and window components
import android.content.Context;
import android.graphics.Point;
import android.view.WindowManager;
/*
@author Filip Bongcam
DEVICE METRICS
Collects useful data of the device physical screen and window components
@param context
*/
public class DeviceMetrics {
private Context context;
// System UI
private int status_bar_height;
private int navigation_bar_height;
// Display
private float displayDensity;
private int displayHeight_real; // Display height with status and navigation bar
private int displayWidth_real;
private int displayHeight; // Display height without status and navigation bar
private int displayWidth;
public DeviceMetrics(Context context)
{
this.context = context;
status_bar_height = context.getResources().getIdentifier("status_bar_height", "dimen","android");
navigation_bar_height = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
// Display density
displayDensity = context.getResources().getDisplayMetrics().density;
displayHeight = context.getResources().getDisplayMetrics().heightPixels;
displayWidth = context.getResources().getDisplayMetrics().widthPixels;
// Physical screen size in px
Point points = new Point();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getRealSize(points);
displayHeight_real = points.y;
displayWidth_real = points.x;
}
public int getStatusbar_height()
{
return context.getResources().getDimensionPixelSize(status_bar_height);
}
public int getNavigationbar_height()
{
return context.getResources().getDimensionPixelSize(navigation_bar_height);
}
public int getWindowHeight() { return displayHeight; }
public int getWindowWidth() { return displayWidth; }
public int getDisplayHeight()
{
return displayHeight_real;
}
public int getDisplayWidth()
{
return displayWidth_real;
}
/*
Converts px to dp based on display desnsity
Source: https://stackoverflow.com/questions/4605527/converting-pixels-to-dp
*/
public float dpFromPx(float px) {
return px / displayDensity;
}
/*
Converts dp to px based on display desnsity
Source: https://stackoverflow.com/questions/4605527/converting-pixels-to-dp
*/
public float pxFromDp(float dp) {
return dp * displayDensity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment