一:获取状态栏高度(一般为38px)
decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。
于是,我们就可以算出状态栏的高度了。
Rect frame = new Rect(); getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top;
二:获取标题栏高度(一般为72px)
getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); //statusBarHeight是上面所求的状态栏的高度 int titleBarHeight = contentTop - statusBarHeight;
注意:
上述使用,在Activity的生命周期onCreate()和onResume()方法中调用,返回值可能出现为0的情况,建议使用:
public static int getStatusBarHeight(Activity activity) { Class<?> c = null; Object obj = null; Field field = null; int x = 0, sbar = 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()); sbar = activity.getResources().getDimensionPixelSize(x); } catch(Exception e1) { Log.e("StatusBarHeight","get status bar height fail"); e1.printStackTrace(); } Log.i("StatusBarHeight", "" + sbar); return sbar; }
三:获取屏幕密度和宽高
但是,需要注意的是,在一个低密度的小屏手机上,仅靠上面的代码是不能获取正确的尺寸的。比如说,一部240x320像素的低密度手机,如果运行上述代码,获取到的屏幕尺寸是320x427。因此,研究之后发现,若没有设定多分辨率支持的话,Android系统会将240x320的低密度(120)尺寸转换为中等密度(160)对应的尺寸,这样的话就大大影响了程序的编码。所以,需要在工程的AndroidManifest.xml文件中,加入supports-screens节点,具体的内容如下:DisplayMetrics dMetrics = new DisplayMetrics(); getWindow().getWindowManager().getDefaultDisplay().getMetrics(dMetrics); int screentWidth = dMetrics.widthPixels; //屏幕宽度(像素) int screentHeight = dMetrics.heightPixels; // 屏幕高度(像素) float screentDensity = dMetrics.density; // 屏幕密度(0.75 / 1.0 / 1.5) int screentDensityDpi = dMetrics.densityDpi; <span style="white-space:pre"> </span>// 屏幕密度DPI(120 / 160 / 240)
这样的话,当前的Android程序就支持了多种分辨率,那么就可以得到正确的物理尺寸了。<supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:resizeable="true" android:anyDensity="true" />