How to get screen dimensions

31 Views Asked by At

So I have an app which defines an ImageView within a LinearLayout. The ImageView and LinearLayout width and height are specified to be "match_parent" and the ImageView does appear to be the same dimensions as the screen. However, when I try to get the dimensions of the screen in order to create and attach a bitmap to the ImageView, the height matches the height of the screen but the width comes back slightly less than the width of the screen. I am using the following code to get the width and height.

    val width = resources.displayMetrics.widthPixels
    val height = resources.displayMetrics.heightPixels

There is also this:

windowManager.currentWindowMetrics.bounds.width()
windowManager.currentWindowMetrics.bounds.height()

but this requires API level 30 (I want my app to be able to run from API level 24), and even if I do increase the minimum API level to 30, that gives the incorrect value for width as well.

The same thing happens if I use this:

    val width = windowManager.maximumWindowMetrics.bounds.width()
    val height = windowManager.maximumWindowMetrics.bounds.height()

And this is deprecated:

windowManager.defaultDisplay

So I'm not really sure how to get the correct screen width. For the record, the code to create the bitmap looks like this:

        val bitmap = Bitmap.createBitmap(width.toInt(), height.toInt(), Bitmap.Config.ARGB_8888)

I'm now wondering (after posting the question) if using a ViewTreeObserver to get the dimensions of the ImageView (which is the same size as the screen) would work, but it seems like there should be a simpler way to do this.

1

There are 1 best solutions below

0
Chris B On

This works:

        val mainLayout: LinearLayout = findViewById(R.id.main_layout)
        mainLayout.viewTreeObserver.addOnGlobalLayoutListener(
        object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val imageView = findViewById<ImageView>(R.id.image_view)
                val width = imageView.width
                val height = imageView.height
                // do initialization
            }
        }
    )
}

This is the same thing using a lambda expression:

        val mainLayout: LinearLayout = findViewById(R.id.main_layout)
        mainLayout.viewTreeObserver.addOnGlobalLayoutListener {
        val imageView = findViewById<ImageView>(R.id.image_view)
        val width = imageView.width
        val height = imageView.height
        // do initialization
    }