Android 获取window状态栏和标题栏的高度

缩放图片,需要获取屏幕区域的大小,就需要获取android 状态栏的高度

方法有两种:

1.网络上最常见的方法:

Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;

 decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。 于是,我们就可以算出状态栏的高度了。

注意:可能获取的高度值为0,

原因:

由于窗口view的绘制需要一定的时延,所以在获取状态栏高度的时候在窗口的可视阶段即从oncreate()->onresume()都不能直接使用上面的方法。解决方法有3种:
1.可以放在一个button的OnClickListener下的onClick()方法里面;
2.当然你也可以在onPause()->onDestroy()里面去获取

3.用一个handler  示例代码:

在onCreate()方法里面执行:
mHandler.postDelayed(r, 200);

Runnable r = new Runnable() {
        @Override
        public void run() {
            Rect frame = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            int statusBarHeight = frame.top;
            Log.d(TAG, "&&&& " + statusBarHeight);
        }
    };

2.另一种不常见的方法

		try{
			Class<?> cl = Class.forName("com.android.internal.R$dimen");
			Object obj = cl.newInstance();
			Field field = cl.getField("status_bar_height");

			int x = Integer.parseInt(field.get(obj).toString());
			int statusBar = context.getResources().getDimensionPixelSize(x); //状态栏的 高度
			
			Log.v(TAG,"statusBar height: " + statusBar);
		}catch(Exception e){
			e.printStackTrace();
		}

根据:
frameworks\core\res\values\dimens.xml
<dimen name="status_bar_height">25dip</dimen>


附加:

3.获取标题栏高度:


getWindow().findViewById(windows.iD_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。

int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();  
  //statusBarHeight是上面所求的状态栏的高度  
  int titleBarHeight = contentTop - statusBarHeight  


frameworks\core\res\values\themes.xml
<item name="windowTitleSize">25dip</item>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值