Search code examples
androidscreen-sizemeasurement

Android: determining screen size in different ways cause different screen sizes


When I determine the screen size in an Activity with this attempt, I get 800x480 as result:

@SuppressWarnings("deprecation")
private void initSpecs()
{
    WindowManager windowManager = (WindowManager)this.getSystemService(Context.WINDOW_SERVICE);
    Point size = new Point();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
    {
        windowManager.getDefaultDisplay().getSize(size);

        effectiveWidth = size.x;
        effectiveHeight = size.y;
    }
    else
    {
        Display display = windowManager.getDefaultDisplay();

        effectiveWidth = display.getWidth();
        effectiveHeight = display.getHeight();
    }
}

When I determine the screen size in my game view (a class extending view) with the following attempt, I get 800x442.

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
}

There is NO title bar. How does this discrepancy emerge?


Solution

  • Well the problem is that in the first way you are actually getting the "screen/display" size, however, In the second way what you are getting is the width/height measured values of the View where you overrode the "onMeasure", and that's not necessarily equal to the screen size, specially if another Views affect the size of your View during it's life cycle. This is kind of the life cycle of a View.

    • Attached
    • Measured*
    • Layout
    • Drawn

    Notice that there's a chance this life cycle repeats if another View changes it's size and the OS thinks is a good idea to refresh the views.

    Hope it Helps!

    Regards!