一大波干货来袭,屏幕尺寸各种获得,状态栏尺寸可正确获得,亲测。
package com.elyar.app.util.measure; import java.lang.reflect.Field; import android.app.Activity; import android.util.DisplayMetrics; public class DisplayMeasure { /** * Note:个人经验不服来辩<br> * 只有activity可以使用getWindowManager,否则应该使用<br> * Context.getResources().getDisplayMetrics()来获取.<br> * * @author ElyarAnwar 2016-1-29 21:24 Aksu * */ public DisplayMeasure() { } /** * 获取屏幕尺寸,单位为像素 * @param context Activity的上下文 * @return 屏幕宽度 单位PX */ public static int getScreenWidthPixel(Activity context){ DisplayMetrics outMetrics = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(outMetrics); int widthPixels = outMetrics.widthPixels; return widthPixels; } /** * 获取屏幕尺寸,单位为像素 * @param context Activity的上下文 * @return 屏幕高度 单位PX */ public static int getScreenHeightPixel(Activity context){ DisplayMetrics outMetrics = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(outMetrics); int heightPixels = outMetrics.heightPixels; return heightPixels; } /** * 获取屏幕尺寸,单位为dp * @param context Activity的上下文 * @return 屏幕宽度 单位Dp */ public static int getScreenWidthInDp(Activity context){ DisplayMetrics outMetrics = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(outMetrics); int widthDp = outMetrics.widthPixels; return ChangeUnits.px2dp(context, widthDp);//将PX转换成Dp } /** * 获取屏幕尺寸,单位为dp * @param context Activity的上下文 * @return 屏幕高度 单位Dp */ public static int getScreenHeightInDp(Activity context){ DisplayMetrics outMetrics = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(outMetrics); int heightDp = outMetrics.heightPixels; return ChangeUnits.px2dp(context, heightDp); } /** * 获取状态栏高度 * @param context 上下文 * @return 状态栏高度 单位像素 */ public static int getStatusBarHeightPixel(Activity context){ Class<?> c = null; Object obj = null; Field field = null; int x = 0, statusBarHeight = 0; try { c = Class.forName("com.android.internal.R$dimen"); obj = c.newInstance(); field = c.getField("status_bar_height"); x = Integer.parseInt(field.get(obj).toString()); statusBarHeight = context.getResources().getDimensionPixelSize(x); } catch (Exception e1) { e1.printStackTrace(); } return statusBarHeight; } /** * 获取状态栏高度 * @param context 上下文 * @return 状态栏高度 单位dp */ public static int getStatusBarHeightInDp(Activity context){ Class<?> c = null; Object obj = null; Field field = null; int x = 0, statusBarHeight = 0; try { c = Class.forName("com.android.internal.R$dimen"); obj = c.newInstance(); field = c.getField("status_bar_height"); x = Integer.parseInt(field.get(obj).toString()); statusBarHeight = context.getResources().getDimensionPixelSize(x); } catch (Exception e1) { e1.printStackTrace(); } return ChangeUnits.px2dp(context, statusBarHeight); } }