1.获取状态栏高度:
decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。
于是,我们就可以算出状态栏的高度了。
- 1. Rect frame = new Rect();
-
2. getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
-
3. int statusBarHeight = frame.top;
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
2.获取标题栏高度:
getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。
- # int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
-
# //statusBarHeight是上面所求的状态栏的高度
-
# int titleBarHeight = contentTop - statusBarHeight
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight
例子代码:
- 1. package com.cn.lhq;
-
2. import android.app.Activity;
-
3. import android.graphics.Rect;
-
4. import android.os.Bundle;
-
5. import android.util.Log;
-
6. import android.view.Window;
-
7. import android.widget.ImageView;
-
8. public class Main extends Activity {
-
9. ImageView iv;
-
10. @Override
-
11. public void onCreate(Bundle savedInstanceState) {
-
12. super.onCreate(savedInstanceState);
-
13. setContentView(R.layout.main);
-
14. iv = (ImageView) this.findViewById(R.id.ImageView01);
-
15. iv.post(new Runnable() {
-
16. public void run() {
-
17. viewInited();
-
18. }
-
19. });
-
20. Log.v("test", "== ok ==");
-
21. }
-
22. private void viewInited() {
-
23. Rect rect = new Rect();
-
24. Window window = getWindow();
-
25. iv.getWindowVisibleDisplayFrame(rect);
-
26. int statusBarHeight = rect.top;
-
27. int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT)
-
28. .getTop();
-
29. int titleBarHeight = contentViewTop - statusBarHeight;
-
30. // 测试结果:ok之后 100多 ms 才运行了
-
31. Log.v("test", "=-init-= statusBarHeight=" + statusBarHeight
-
32. + " contentViewTop=" + contentViewTop + " titleBarHeight="
-
33. + titleBarHeight);
-
34. }
-
35. }
- # <?xml version="1.0" encoding="utf-8"?>
-
# <LinearLayout xmlns:android=""
-
# android:orientation="vertical"
-
# android:layout_width="fill_parent"
-
# android:layout_height="fill_parent">
-
# <ImageView
-
# android:id="@+id/ImageView01"
-
# android:layout_width="wrap_content"
-
# android:layout_height="wrap_content"/>
-
# </LinearLayout>