背景介绍:

到目前为止,android已经从1.5发展到目前的3.2,我们在写一个应用的时候,最常用到得就是获取屏幕高度,宽度,以及status bar的高度。

然而android系统变化太快了,从开始的手机操作系统到目前的3.2 平板电脑系统,在获取这些数据的时候也发生了很大的变化。

值得我们重视,否则会有很多错误发生。


问题分析及解决方案:

1. android 1.6 到 android 2.x

这是android手机操作系统,从1.6到2.x都有着统一的获取方法。

直接利用android api即可获取相关的尺寸,

WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);

int width = wm.getDefaultDisplay().getWidth();//屏幕宽度

int height = wm.getDefaultDisplay().getHeight();//屏幕高度

Rect rect= new Rect(); 

this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); 

int statusBarHeight = rect.top; //状态栏高度


2. android 3.0 平板系统

在3.0系统中,status bar在屏幕下方,因为计算方法也发生改变。

在3.0系统中获取屏幕高度和宽度的方法没有改变。

状态的获取方法如下:

Rect rect= new Rect(); 

this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); 


int statusBarHeight = window.getWindowManager().getDefaultDisplay().getHeight() - rect.bottom;

即利用屏幕高度减去显示区域的最大高度即为下方status bar的高度


3. android 3.2平板系统

在android 3.2中就有了很大的改变,当我们调用getWidth()和getheight()获取宽度和高度的时候,不会返回屏幕的真实尺寸,

而是只返回屏幕的显示区域的尺寸,即减去了状态栏的高度。

运用这两个api函数读取的尺寸肯定不是我们想要的结果。

这时我们发现其提供了两个隐藏函数getRealHeight()和getRealWidth()用来获取真实的屏幕尺寸。

一因为是隐藏函数,所以我们只能通过反射来调用这两个函数,但这样带来不好的就是反射效率实在是太差了。

Display display = wm.getDefaultDisplay();
Class c = Class.forName("android.view.Display");

Method method = c.getMethod("getRealHeight");
int height = (Integer) method.invoke(display);

Rect rect= new Rect(); 

this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); 


statusbarHeight = height - rect.bottom;

对上述代码进行优化,如果当我们频繁调用的时候,必将影响程序性能。

我们可以保存第一次反射的相关信息,然后在后面直接调用。


private Method method = null;// 用来保存method对象

---------------------------------------------------------------------------------

Display display = wm.getDefaultDisplay();

//判断method是否为空,如果为null,则利用反射得到method信息,否则,利用旧的method对象。
if(method == null)
{

        method = display.getClass().getMethod("getRealHeight"); //这里直接用display的class信息

}


int height = (Integer) method.invoke(display);

Rect rect= new Rect(); 

this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); 


如果这篇文章帮助到您,就请您打赏一杯饮料钱吧。

android 获取屏幕高度,宽度,状态栏高度_第1张图片











更多相关文章

  1. Android适配(屏幕适配、国际化适配)
  2. 屏幕适配全攻略
  3. Android开发屏幕适配全攻略
  4. android 布局如何支持多种不同屏幕尺寸
  5. 安卓热点话题总结性剖析:《Android在多屏幕、多设备上的适配》 |
  6. Android 超简单的录制屏幕视频及生成GIF文件的方法

随机推荐

  1. Android Permissions - Protection Level
  2. android 学习电子书——下载
  3. android调用Google搜索框
  4. Ubuntu 12.10 搭建 Eclipse Android(安卓
  5. android 3.0编译环境需要的所有组件
  6. Android文件保存和读取
  7. android 中添加 admob 广告
  8. android用代码实现圆角背景
  9. Android Google App
  10. android 蓝牙各种UUID