Device dimensions in Kotlin not java

Viewed 1484

How do I calculate the dimensions of an Android device in kotlin?

I have tried:

val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
 
var width = displayMetrics.widthPixels
var height = displayMetrics.heightPixels

It gives me the following error:

"getter for defaultDisplay: Display!' is deprecated. Deprecated in Java:"

Thank you

3 Answers

The new way to do it now is with context, This method is the one I used to obtain the real height, depending on the orientation of the screen

Note * Make sure for the context of an activity or fragment

fun getDisplayHeight(context: Context): Int {


   val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
   val displayMetrics = DisplayMetrics()


    try {

        context.display?.getRealMetrics(displayMetrics)
    } catch (e: NoSuchMethodError) {
        windowManager.defaultDisplay.getRealMetrics(displayMetrics)
    }


    return if (context.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            minOf(displayMetrics.widthPixels, displayMetrics.heightPixels)
        } else {
            maxOf(displayMetrics.widthPixels, displayMetrics.heightPixels)
        }

}
Related