gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:07:52 25 4
gpt4 key购买 nike

我使用了下面的代码,但一些分辨率如 Nexus 5(lolipop - 5.0)、设备高度和宽度没有返回实际值。
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);<br/>
width = metrics.heightPixels;
height = metrics.widthPixels;

最佳答案

我使用以下实用函数:

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));
}

关于Android获取所有分辨率的设备屏幕高度和宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27374049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com