缩放图片,需要获取屏幕区域的大小,就需要获取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
<item name="windowTitleSize">25dip</item> | frameworks\core\res\values\themes.xml