Display metrics minus status bar?

后端 未结 2 779
温柔的废话
温柔的废话 2020-12-08 09:59

I need to get the dimensions of the display rectangle that the application can use on the device. For that I tried using:

Display display = getWindowManager(         


        
2条回答
  •  清歌不尽
    2020-12-08 10:30

    This call is independent of the point of time you call it:

    ...
    Point dimensions = getDisplayDimensions(context);
    int width = dimensions.x;
    int height = dimensions.y;
    ...
    
    @NonNull
    public static Point getDisplayDimensions( Context context )
    {
        WindowManager wm = ( WindowManager ) context.getSystemService( Context.WINDOW_SERVICE );
        Display display = wm.getDefaultDisplay();
    
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics( metrics );
        int screenWidth = metrics.widthPixels;
        int screenHeight = metrics.heightPixels;
    
        // find out if status bar has already been subtracted from screenHeight
        display.getRealMetrics( metrics );
        int physicalHeight = metrics.heightPixels;
        int statusBarHeight = getStatusBarHeight( context );
        int navigationBarHeight = getNavigationBarHeight( context );
        int heightDelta = physicalHeight - screenHeight;
        if ( heightDelta == 0 || heightDelta == navigationBarHeight )
        {
            screenHeight -= statusBarHeight;
        }
    
        return new Point( screenWidth, screenHeight );
    }
    
    public static int getStatusBarHeight( Context context )
    {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier( "status_bar_height", "dimen", "android" );
        return ( resourceId > 0 ) ? resources.getDimensionPixelSize( resourceId ) : 0;
    }
    
    public static int getNavigationBarHeight( Context context )
    {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier( "navigation_bar_height", "dimen", "android" );
        return ( resourceId > 0 ) ? resources.getDimensionPixelSize( resourceId ) : 0;
    }
    

    The trick is that it compares the screen display metrics (what you want modulo the status bar) and the "real metrics", which is the physical pixels of the device.

    The status bar height then is subtracted ad-hoc if that did not happen yet.

    (In my tests the navigation bar, containing back and home buttons, was already subtracted.)

提交回复
热议问题