-
-
Save nesquena/318b6930aac3a56f96a4 to your computer and use it in GitHub Desktop.
Device dimensions utility class for Android
This file contains 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 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