获取屏幕宽高的一种方法

废话不多说,直接上代码

        int realWidth = 0;//宽
        int realHeight = 0;//高
        Display display = context.getWindowManager().getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        if (android.os.Build.VERSION.SDK_INT >= 17) {
            Point size = new Point();
            display.getRealSize(size);
            realWidth = size.x;
            realHeight = size.y;
        } else if (android.os.Build.VERSION.SDK_INT < 17
                && android.os.Build.VERSION.SDK_INT >= 14) {
            try {
                Method mGetRawH =Display.class.getMethod("getRawHeight");
                Method mGetRawW = Display.class.getMethod("getRawWidth");
                realWidth = (Integer) mGetRawW.invoke(display);
                realHeight = (Integer) mGetRawH.invoke(display);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            realWidth = metrics.widthPixels;
            realHeight = metrics.heightPixels;
        }

你可能感兴趣的:(获取屏幕宽高的一种方法)