Android 即使不推荐使用 .getWidth 在 Display 上使用它是否安全

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12780384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 12:04:27  来源:igfitidea点击:

Is it safe to use .getWidth on Display even though its deprecated

androidwidthdeprecated

提问by gabrjan

So i have a small problem, i'm writing a function which need to send screen width to server. I got it all to work, and i use:

所以我有一个小问题,我正在编写一个需要将屏幕宽度发送到服务器的函数。我让它全部工作,我使用:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();

to get width. However .getWidht() function is deprecated and it says u need to use:

得到宽度。但是 .getWidht() 函数已被弃用,它说你需要使用:

Point size = new Point();
display.getSize(size);

But that function is only avaible for api level 13 or more, and my minimum sdk is 8. So what can i do? Is it safe if i stay with getWidth? Why adding new function and not make them backward compatible?

但该功能仅适用于 13 级或更高级别的 api,而我的最小 sdk 是 8。那我该怎么办?如果我继续使用 getWidth 是否安全?为什么添加新功能而不是使它们向后兼容?

回答by iBog

May be this approach will be helpful:

可能这种方法会有所帮助:

DisplayMetrics displaymetrics = new DisplayMetrics();
mContext.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int screenWidth = displaymetrics.widthPixels;
int screenHeight = displaymetrics.heightPixels;

回答by nmw

You can check for API level at runtime, and choose which to use, e.g.:

您可以在运行时检查 API 级别,并选择要使用的级别,例如:

final int version = android.os.Build.VERSION.SDK_INT;
final int width;
if (version >= 13)
{
    Point size = new Point();
    display.getSize(size);
    width = size.x;
}
else
{
    Display display = getWindowManager().getDefaultDisplay(); 
    width = display.getWidth();
}

回答by slezadav

If you want to be correct, use this approach>

如果您想正确,请使用此方法>

           int sdk = android.os.Build.VERSION.SDK_INT;
            if (sdk < android.os.Build.VERSION.RELEASE) {
                Display display = getWindowManager().getDefaultDisplay();
                int width = display.getWidth();

            } else {
                Point size = new Point();
                display.getSize(size);

            }