您的位置:首页 > 移动开发 > Android开发

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

2015-04-27 00:06 302 查看
缩放图片,需要获取屏幕区域的大小,就需要获取android 状态栏的高度

方法有两种:

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

[java] view
plaincopy

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);

[java] view
plaincopy

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.另一种不常见的方法

[java] view
plaincopy

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就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。

[java] view
plaincopy

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>
http://blog.csdn.net/go_to_learn/article/details/8562840
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: