Get the screen height in Android

前端 未结 9 1188
忘了有多久
忘了有多久 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.

    0 讨论(0)
  • 2021-02-05 10:33

    If you want the the display dimensions in pixels you can use getSize:

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;
    

    If you're not in an Activity you can get the default Display via WINDOW_SERVICE:

    WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    display.getSize(size);
    int width = size.x;
    int height = size.y;
    

    Before getSize was introduced (in API level 13), you could use the getWidth and getHeight methods that are now deprecated:

    Display display = getWindowManager().getDefaultDisplay(); 
    int width = display.getWidth();  // deprecated
    int height = display.getHeight();  // deprecated
    

    Referred from : Get screen dimensions in pixels

    0 讨论(0)
  • 2021-02-05 10:33
    Display currentDisplay = getWindowManager().getDefaultDisplay();
            float dw = currentDisplay.getWidth();
            float dh = currentDisplay.getHeight();
    

    dh will give you the screen height.

    0 讨论(0)
提交回复
热议问题