display.getRealMetrics() 已弃用

display.getRealMetrics() is deprecated

我正在使用 getRealMetrics() 方法,后来知道它已被弃用

val display = this.display
display?.getRealMetrics(outMetrics)

有人知道替代方案是什么。

https://developer.android.com/reference/android/view/Display

getRealMetrics(DisplayMetrics outMetrics)

This method was deprecated in API level 31. Use WindowManager#getCurrentWindowMetrics() to identify the current size of the activity window. UI-related work, such as choosing UI layouts, should rely upon WindowMetrics#getBounds(). Use Configuration#densityDpi to get the current density.

试试这个

Resources.getSystem().displayMetrics

对于宽度和高度

Resources.getSystem().displayMetrics.widthPixels
Resources.getSystem().displayMetrics.heightPixels

使用WindowMetricsCalculator获取显示高度和宽度参数

dependencies {
implementation "androidx.window:window:1.0.0-beta02"}


val windowMetrics = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(activity)
val currentBounds = windowMetrics.bounds

val width = currentBounds.width()
val height = currentBounds.height()

根据官方docs推荐的方式是使用WindowManager#getCurrentWindowMetrics():

val metrics: WindowMetrics = context.getSystemService(WindowManager::class.java).currentWindowMetrics

如果你用它来获取屏幕尺寸,请看我的回答here

您好,我在 xamarin.android 中创建了这个函数:(清单 SDK 最大 31,最小 25)

public bool IsTablet()
    {
        var displayMetrics = Resources.DisplayMetrics;
        var defaultDisplay = WindowManager.DefaultDisplay;
        double widthPixels = 0;
        double heightPixels = 0;

        if (Build.VERSION.SdkInt >= BuildVersionCodes.S) //API 31 and more
        {
            var windowMetrics = WindowManager.CurrentWindowMetrics;

            Rect bounds = windowMetrics.Bounds;
            widthPixels = bounds.Width();
            heightPixels = bounds.Height();   
        }
        if (Build.VERSION.SdkInt == BuildVersionCodes.R) //API 30
        {
            #pragma warning disable
            defaultDisplay.GetRealMetrics(displayMetrics);

            widthPixels = displayMetrics.WidthPixels;
            heightPixels = displayMetrics.HeightPixels;
        }
        if (Build.VERSION.SdkInt < BuildVersionCodes.R) //less then 30
        {
            #pragma warning disable
            defaultDisplay.GetMetrics(displayMetrics);

            widthPixels = displayMetrics.WidthPixels;
            heightPixels = displayMetrics.HeightPixels;
        }

        var wInches1 = widthPixels / (double)displayMetrics.DensityDpi;
        var hInches1 = heightPixels / (double)displayMetrics.DensityDpi;

        double inch = Math.Sqrt(Math.Pow(wInches1, 2) + Math.Pow(hInches1, 2));

        if (cale >= 7.0)
        {
            tablet = true;
        }

        return tablet;
    }