Android获取所有分辨率的设备屏幕高度和宽度

时间:2014-12-09 08:07:26

标签: android screen

我使用了以下代码,但是一些分辨率如Nexus 5(棒棒糖 - 5.0),设备高度和宽度都没有返回实际值。 DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics);
width = metrics.heightPixels; height = metrics.widthPixels;

3 个答案:

答案 0 :(得分:4)

我使用以下实用程序函数:

private static int sScreenWidthDP = -1;
private static int sScreenWidth = -1;
private static int sScreenHeight = -1;

public static int getScreenHeight(Context context) {
        if (sScreenHeight == -1) {
            Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            sScreenHeight = size.y;
        }
        return sScreenHeight;
    }

    public static int getScreenHeightInDp(Context context) {
        if (sScreenHeight == -1) {
            Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            sScreenHeight = size.y;
        }
        return pixelsToDp(context, sScreenHeight);
    }

    public static int getScreenWidthInDp(Context context) {
        if (sScreenWidthDP == -1) {
            Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            sScreenWidthDP = pixelsToDp(context, size.x);
        }
        return sScreenWidthDP;
    }
public static int getScreenWidth(Context context) {
        if (sScreenWidth == -1) {
            Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            sScreenWidth = size.x;
        }

        return sScreenWidth;
    }
public static float dpToPixels(Context context, int dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
    }

    public static int pixelsToDp(Context context, float pixels) {
        float density = context.getResources().getDisplayMetrics().densityDpi;
        return Math.round(pixels / (density / 160f));
    }

答案 1 :(得分:0)

我使用以下代码获取宽度或高度

    WindowManager wm = (WindowManager) context
            .getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);

    int height = size.y;
    int width = size.x;

答案 2 :(得分:0)

尝试以下方式,它可以让您获得设备的实际尺寸:

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getRealSize(size);
    int width = size.x;
    int height = size.y;