gpt4 book ai didi

android - getSize() 在 API 级别 30 中已弃用

转载 作者:行者123 更新时间:2023-12-04 12:08:04 27 4
gpt4 key购买 nike

我使用 getSize() 方法来获取屏幕尺寸:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val fragmentActivity = requireActivity()
...
val wm = fragmentActivity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
fragmentActivity.display
} else {
wm.defaultDisplay
}
val size = Point()
display?.getSize(size)

// get screen sizes
val width = size.x
val height = size.y
...
}
但是在 API 级别 30 中,声明方法 getSize() 已弃用。
可以使用什么代替 getSize() 来获取屏幕尺寸?
感谢您的任何评论/回答!
解决方案 :
val wm = fragmentActivity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val width: Int
val height: Int
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val windowMetrics = wm.currentWindowMetrics
val windowInsets: WindowInsets = windowMetrics.windowInsets

val insets = windowInsets.getInsetsIgnoringVisibility(
WindowInsets.Type.navigationBars() or WindowInsets.Type.displayCutout())
val insetsWidth = insets.right + insets.left
val insetsHeight = insets.top + insets.bottom

val b = windowMetrics.bounds
width = b.width() - insetsWidth
height = b.height() - insetsHeight
} else {
val size = Point()
val display = wm.defaultDisplay // deprecated in API 30
display?.getSize(size) // deprecated in API 30
width = size.x
height = size.y
}

最佳答案

如果像我一样,您只想获取窗口大小,这里有一个兼容版本:

fun WindowManager.currentWindowMetricsPointCompat(): Point {
return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
val windowInsets = currentWindowMetrics.windowInsets
var insets: Insets = windowInsets.getInsets(WindowInsets.Type.navigationBars())
windowInsets.displayCutout?.run {
insets = Insets.max(insets, Insets.of(safeInsetLeft, safeInsetTop, safeInsetRight, safeInsetBottom))
}
val insetsWidth = insets.right + insets.left
val insetsHeight = insets.top + insets.bottom
Point(currentWindowMetrics.bounds.width() - insetsWidth, currentWindowMetrics.bounds.height() - insetsHeight)
}else{
Point().apply {
defaultDisplay.getSize(this)
}
}
}
它将负责删除导航栏的插图并显示剪切区域以在两种情况下获得相同的结果

关于android - getSize() 在 API 级别 30 中已弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63719160/

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