vuhung3990
7/6/2015 - 5:36 PM

getScreenSize.java

private void setScreenSize() {
        Display display = ((Activity) context).getWindowManager().getDefaultDisplay();

        if (Build.VERSION.SDK_INT >= 17) {
            //new pleasant way to get real metrics
            DisplayMetrics realMetrics = new DisplayMetrics();
            display.getRealMetrics(realMetrics);
            width = realMetrics.widthPixels;
            height = realMetrics.heightPixels;

        } else if (Build.VERSION.SDK_INT >= 14) {
            //reflection for this weird in-between time
            try {
                Method mGetRawH = Display.class.getMethod("getRawHeight");
                Method mGetRawW = Display.class.getMethod("getRawWidth");
                width = (Integer) mGetRawW.invoke(display);
                height = (Integer) mGetRawH.invoke(display);
            } catch (Exception e) {
                //this may not be 100% accurate, but it's all we've got
                width = display.getWidth();
                height = display.getHeight();
            }

        } else {
            //This should be close, as lower API devices should not have window navigation bars
            width = display.getWidth();
            height = display.getHeight();
        }

        // when landscape w > h, swap it
        if (width > height) {
            int temp = width;
            width = height;
            height = temp;
        }
    }