android api26获得状态栏高度,获取statusBar(状态栏)高度的几个方法

Rect frame = new Rect();

getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

int statusBarHeight = frame.top;

首先是这个api,但是这个方法有个局限性,在onCreate()以及到onResume()的生命周期里面执行的话,获取的高度为0,因为这个decorView的绘制需要时间,所以我们需要延时使用该方法来获取高度;

new Runnable(){

@Override

public void run(){

Rect frame = new Rect();

getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

int statusBarHeight = frame.top;

}

}

然后可以用handler.postDelayed(run,200)去执行,就能获得statusBar的高度了,这个200毫秒其实应该是大大超过了decorView的绘制时间了,因为View的绘制时间超过了16.7ms就会出现卡顿的现象,人眼来识别的话,每秒需要达到60帧,画面才会流畅。但是,经过测试,100毫秒左右是没问题的。这个怎么会要这么久的时间去绘制,不是很懂

我们应该使用一个在任何时候都能正常获取到statusBar高度的方法,这样应用才不会出一些奇奇怪怪的问题。

Resources resources = getResources();

int resourceId = resources.getIdentifier("status_bar_height", "dimen","android");

int height = resources.getDimensionPixelSize(resourceId);

这个api在任何时候都能正常获取到高度,其实是调用native方法。还有一种是用java的反射来获取高度的:

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;

这个方法没有试过,看上去和第二个方法很像,获取的包名,类名和字段名都一模一样。

2016年4月22日

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值