Skip to content

Instantly share code, notes, and snippets.

@nesquena
Last active April 5, 2021 06:33
Show Gist options
  • Save nesquena/318b6930aac3a56f96a4 to your computer and use it in GitHub Desktop.
Save nesquena/318b6930aac3a56f96a4 to your computer and use it in GitHub Desktop.
Device dimensions utility class for Android
public class DeviceDimensionsHelper {
// DeviceDimensionsHelper.getDisplayWidth(context) => (display width in pixels)
public static int getDisplayWidth(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return displayMetrics.widthPixels;
}
// DeviceDimensionsHelper.getDisplayHeight(context) => (display height in pixels)
public static int getDisplayHeight(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return displayMetrics.heightPixels;
}
// DeviceDimensionsHelper.convertDpToPixel(25f, context) => (25dp converted to pixels)
public static float convertDpToPixel(float dp, Context context){
Resources r = context.getResources();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
}
// DeviceDimensionsHelper.convertPixelsToDp(25f, context) => (25px converted to dp)
public static float convertPixelsToDp(float px, Context context){
Resources r = context.getResources();
DisplayMetrics metrics = r.getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return dp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment