Chinaunix首页 | 论坛 | 博客
  • 博客访问: 285904
  • 博文数量: 68
  • 博客积分: 1474
  • 博客等级: 上尉
  • 技术积分: 616
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-12 12:07
文章分类

全部博文(68)

文章存档

2011年(68)

分类: 嵌入式

2011-02-28 15:23:49

1.获取状态栏高度:

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

  1. 1. Rect frame = new Rect();
  2.    2. getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
  3.    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就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。

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

例子代码:

  1. 1. package com.cn.lhq;
  2.    2. import android.app.Activity;
  3.    3. import android.graphics.Rect;
  4.    4. import android.os.Bundle;
  5.    5. import android.util.Log;
  6.    6. import android.view.Window;
  7.    7. import android.widget.ImageView;
  8.    8. public class Main extends Activity {
  9.    9. ImageView iv;
  10.   10. @Override
  11.   11. public void onCreate(Bundle savedInstanceState) {
  12.   12. super.onCreate(savedInstanceState);
  13.   13. setContentView(R.layout.main);
  14.   14. iv = (ImageView) this.findViewById(R.id.ImageView01);
  15.   15. iv.post(new Runnable() {
  16.   16. public void run() {
  17.   17. viewInited();
  18.   18. }
  19.   19. });
  20.   20. Log.v("test", "== ok ==");
  21.   21. }
  22.   22. private void viewInited() {
  23.   23. Rect rect = new Rect();
  24.   24. Window window = getWindow();
  25.   25. iv.getWindowVisibleDisplayFrame(rect);
  26.   26. int statusBarHeight = rect.top;
  27.   27. int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT)
  28.   28. .getTop();
  29.   29. int titleBarHeight = contentViewTop - statusBarHeight;
  30.   30. // 测试结果:ok之后 100多 ms 才运行了
  31.   31. Log.v("test", "=-init-= statusBarHeight=" + statusBarHeight
  32.   32. + " contentViewTop=" + contentViewTop + " titleBarHeight="
  33.   33. + titleBarHeight);
  34.   34. }
  35.   35. }

  1. # <?xml version="1.0" encoding="utf-8"?>
  2. # <LinearLayout xmlns:android=""
  3. # android:orientation="vertical"
  4. # android:layout_width="fill_parent"
  5. # android:layout_height="fill_parent">
  6. # <ImageView
  7. # android:id="@+id/ImageView01"
  8. # android:layout_width="wrap_content"
  9. # android:layout_height="wrap_content"/>
  10. # </LinearLayout>


阅读(1871) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~