display.getRealMetrics() 已经被弃用。

8

我正在使用getRealMetrics()方法,但得知它已被弃用。

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

有人知道替代方法是什么吗?


如果您想获取屏幕尺寸,请查看我在此处的答案 https://dev59.com/Vm445IYBdhLWcg3wq8Pp#70087378。这里有一个可维护的用Kotlin编写的获取屏幕尺寸的实现。 - Sergio
5个回答

3

试试这个

Resources.getSystem().displayMetrics

关于宽度和高度

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

1
我该如何使用它来替代display.getRealMetrics(displaymetrics)? - Tariq Hussain
我明白了,谢谢。 - Tariq Hussain

3
根据官方文档,推荐使用WindowManager#getCurrentWindowMetrics()来实现,具体请参考文档
val metrics: WindowMetrics = context.getSystemService(WindowManager::class.java).currentWindowMetrics

如果您想获取屏幕尺寸,请参考我的答案

2
使用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()

1

你好,我在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;
    }

1

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

getRealMetrics(DisplayMetrics outMetrics)

这个方法已在API级别31中弃用。使用WindowManager#getCurrentWindowMetrics()来确定活动窗口的当前大小。与UI相关的工作,例如选择UI布局,应依赖于WindowMetrics#getBounds()。使用Configuration#densityDpi来获取当前密度。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接