Get the screen height in Android

前端 未结 9 1187
忘了有多久
忘了有多久 2021-02-05 09:57

How can I get the available height of the screen in Android? I need to the height minus the status bar / menu bar or any other decorations that might be on screen and I need it

9条回答
  •  囚心锁ツ
    2021-02-05 10:28

    final View view = findViewById(R.id.root);
    ViewTreeObserver vto = view.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            // calculate the height in here...
    
            ViewTreeObserver vto = view.getViewTreeObserver();
            vto.removeGlobalOnLayoutListener(this);
        }
    });
    

    Use this listener inside onCreate (available since api 1). You will need to assign the id @+id/root to the parent in your xml layout. There is no way the size can return a result of 0, since this listener makes a callback whenever the layouts has been positioned in view.

提交回复
热议问题