android 获取屏幕高度,宽度,状态栏高度

背景介绍:

到目前为止,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);  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值