|
| 1 | +package me.brucezz.sample; |
| 2 | + |
| 3 | +import android.content.Context; |
| 4 | +import android.content.res.Resources; |
| 5 | +import android.util.DisplayMetrics; |
| 6 | +import android.util.TypedValue; |
| 7 | + |
| 8 | +/** |
| 9 | + * Created by david on 16/5/26. |
| 10 | + * Email: huangdiv5@gmail.com |
| 11 | + * GitHub: https://github.com/alighters |
| 12 | + */ |
| 13 | +public class DisplayUtil { |
| 14 | + |
| 15 | + private static final String TAG = DisplayUtil.class.getSimpleName(); |
| 16 | + |
| 17 | + private static Context mContext; |
| 18 | + |
| 19 | + public static void init(Context context) { |
| 20 | + mContext = context; |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * 获取屏幕宽度 |
| 25 | + */ |
| 26 | + public static int getScreenWidthPixel() { |
| 27 | + return getDisplayMetrics().widthPixels; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * 获取屏幕高度 |
| 32 | + */ |
| 33 | + public static int getScreenHeightPixel() { |
| 34 | + return getDisplayMetrics().heightPixels; |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * 获取 显示信息 |
| 39 | + */ |
| 40 | + public static DisplayMetrics getDisplayMetrics() { |
| 41 | + return mContext.getResources().getDisplayMetrics(); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * px转dp |
| 46 | + */ |
| 47 | + public static int px2Dp(int px) { |
| 48 | + return (int) (px / getDisplayMetrics().density); |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * px转dp |
| 53 | + */ |
| 54 | + public static int dp2Px(float dpValue) { |
| 55 | + return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, getDisplayMetrics()); |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * sx转dp |
| 60 | + */ |
| 61 | + public static int sp2Px(float spValue) { |
| 62 | + return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, getDisplayMetrics()); |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * 获取状态栏高度 |
| 67 | + */ |
| 68 | + public static int getStatusBarHeight(Context context) { |
| 69 | + int statusBarHeight = 0; |
| 70 | + try { |
| 71 | + int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); |
| 72 | + if (resourceId > 0) { |
| 73 | + statusBarHeight = context.getResources().getDimensionPixelSize(resourceId); |
| 74 | + } |
| 75 | + } catch (Resources.NotFoundException exception) { |
| 76 | + } |
| 77 | + return statusBarHeight; |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * 获取导航栏高度 |
| 82 | + */ |
| 83 | + public static int getNavigationBarHeight(Context context) { |
| 84 | + Resources resources = context.getResources(); |
| 85 | + int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); |
| 86 | + if (resourceId > 0) { |
| 87 | + return resources.getDimensionPixelSize(resourceId); |
| 88 | + } |
| 89 | + return 0; |
| 90 | + } |
| 91 | +} |
0 commit comments