【问题标题】:get statusBar Height in onCreate()在 onCreate() 中获取状态栏高度
【发布时间】:2012-11-10 10:09:43
【问题描述】:

我试图在onCreate 中获取statusBar 高度,但我在这里找到的方法需要已经绘制了一些视图来获取它的大小,然后计算状态栏高度。

由于我在 onCreate 上,所以我还没有绘制任何东西来获得它的大小

有人可以帮我吗?

【问题讨论】:

    标签: java android


    【解决方案1】:
    root = (ViewGroup)findViewById(R.id.root);
    root.post(new Runnable() { 
    public void run(){
        Rect rect = new Rect();
        Window win = getWindow();
        win.getDecorView().getWindowVisibleDisplayFrame(rect);
        int statusHeight = rect.top;
        int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
        int  titleHeight = contentViewTop - statusHeight;
        Log.e("dimen", "title = " + titleHeight + " status bar = " + statusHeight);
    }
    });
    

    【讨论】:

      【解决方案2】:

      使用全局布局监听器

      public void onCreate(Bundle savedInstanceState)
      {
           super.onCreate(savedInstanceState);
      
           // inflate your main layout here (use RelativeLayout or whatever your root ViewGroup type is
           LinearLayout mainLayout = (LinearLayout ) this.getLayoutInflater().inflate(R.layout.main, null); 
      
           // set a global layout listener which will be called when the layout pass is completed and the view is drawn
           mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(
           new ViewTreeObserver.OnGlobalLayoutListener() {
                public void onGlobalLayout() {
                     // measure your views here
                }
           }
       );
      
       setContentView(mainLayout);
      

      [编辑]

      只做一次:

      ViewTreeObserver observer = mainLayout.getViewTreeObserver();
      
      observer.addOnGlobalLayoutListener (new OnGlobalLayoutListener () {
      @Override
      public void onGlobalLayout() {
          // measure your views here
          mainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
         }
       });
      

      【讨论】:

      • 有没有其他方法可以让我只调用一次 measure 方法(在应用启动时)
      • 像我上面那样设置监听器,然后在 onGlobalLayout() 中删除它!请尝试养成阅读 Android 文档的习惯。 developer.android.com/reference/android/view/…
      猜你喜欢
      • 2011-04-22
      • 2013-12-15
      • 2018-06-24
      • 1970-01-01
      • 2018-08-16
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      相关资源
      最近更新 更多