I used the getSize() method to get the screen sizes:
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
...
}
But with API level 30 the method getSize() is declared deprecated.
What can be used instead of getSize() for obtain screen sizes?
Thank you for any comment/answer!
Solution:
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
}
If like me, you just want to get the window size, here is a compat version :
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)
}
}
}
it will take care of removing insets of navigation bars and display cutout areas to get the same result in both case
"Use
WindowManager#getCurrentWindowMetrics()
to obtain an instance of WindowMetrics and use WindowMetrics#getBounds() instead."
It's from Android documentation. Have you read it? [Android doc] https://developer.android.com/reference/android/view/Display#getSize(android.graphics.Point)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With