首页 > 解决方案 > 在android中捕获屏幕大小的正确方法是什么

问题描述

在谷歌上搜索我发现了各种获取屏幕尺寸的方法,这就是我得到的。

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    Log.i(TAG, "first way width = "+size.x);
    Log.i(TAG, "first way height = "+size.y);

    int width = getWindowManager().getDefaultDisplay().getWidth();
    int height = getWindowManager().getDefaultDisplay().getHeight();
    Log.i(TAG, "second way width = "+width);
    Log.i(TAG, "second way height = "+height);

    int height2 = Resources.getSystem().getDisplayMetrics().heightPixels;
    int width2 = Resources.getSystem().getDisplayMetrics().widthPixels;
    Log.i(TAG, "third way width = "+width2);
    Log.i(TAG, "third way height = "+height2);

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int height3 = displaymetrics.heightPixels;
    int width3 = displaymetrics.widthPixels;
    Log.i(TAG, "fourth way width = "+width3);
    Log.i(TAG, "fourth way height = "+height3);  

在记录所有都给出相同的结果。我想知道所有这些方法或任何特定用例之间是否有任何区别?提前致谢。

标签: android

解决方案


不要重新发明轮子使用它,这是检查屏幕高度和宽度的代码:

/**
     * Return the width of screen, in pixel.
     *
     * @return the width of screen, in pixel
     */
    public static int getScreenWidth() {
        WindowManager wm = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE);
        if (wm == null) {
            return Utils.getApp().getResources().getDisplayMetrics().widthPixels;
        }
        Point point = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            wm.getDefaultDisplay().getRealSize(point);
        } else {
            wm.getDefaultDisplay().getSize(point);
        }
        return point.x;
    }

    /**
     * Return the height of screen, in pixel.
     *
     * @return the height of screen, in pixel
     */
    public static int getScreenHeight() {
        WindowManager wm = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE);
        if (wm == null) {
            return Utils.getApp().getResources().getDisplayMetrics().heightPixels;
        }
        Point point = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            wm.getDefaultDisplay().getRealSize(point);
        } else {
            wm.getDefaultDisplay().getSize(point);
        }
        return point.y;
    }

BlankJ从这个帮助库中挑选出来的


推荐阅读