本文介绍了在API级别30(Android 11)上获取屏幕宽度:不建议使用getDefaultDisplay()和getMetrics()。我们应该用什么代替呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前这样计算屏幕宽度:

I currently calculate the screen width like this :

public static int getScreenWidth(@NonNull Context context) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    return displayMetrics.widthPixels;
}

由于这两个函数( getDefaultDisplay() getMetrics ())现在已弃用,我们应该改用什么呢?

Since these 2 functions (getDefaultDisplay() and getMetrics()) are now deprecated, what should we use instead ?

推荐答案

用于计算减去任何系统栏的屏幕宽度,这应该可以正常工作:

For calculating screen width minus any system bars, this should work:

public static int getScreenWidth(@NonNull Activity activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        WindowMetrics windowMetrics = activity.getWindowManager().getCurrentWindowMetrics();
        Insets insets = windowMetrics.getWindowInsets()
                .getInsetsIgnoringVisibility(WindowInsets.Type.systemBars());
        return windowMetrics.getBounds().width() - insets.left - insets.right;
    } else {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }
}

请注意,这并非完全正确。相同:用高度测试它会产生不同的结果,而且我无法用新API复制旧API的功能(部分原因是旧API的行为有点难以解释,并非总是想要的) ,因此已弃用)。不过,实际上,它对于许多事物来说作为通用的屏幕宽度应该足够了。

Note that this isn't exactly the same: testing this with the height produces different results, and I've been unable to replicate the old API's functionality with the new API (partly due to the behavior of the old API being a bit tricky to reason about and not always what you want, hence its deprecation). In practice, though, it should be good enough as a generic screen width for many things.

这篇关于在API级别30(Android 11)上获取屏幕宽度:不建议使用getDefaultDisplay()和getMetrics()。我们应该用什么代替呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:40