android kotlin - Get screen size programmatically

This code snippet demonstrates how to programmatically get the dimensions of the Android device's screen in Kotlin. It provides three methods to achieve this:

  • DisplayMetrics - This is the traditional way of getting the screen size. It retrieves general information about the display, including its width and height in pixels, density, and font scaling.

  • getRealSize - This method is available for API level 30 and above. It retrieves the actual size of the display without any window decor or compatibility scale factors applied.

  • getBounds - This method is also available for API level 30 and above. It retrieves the bounds of the window area, which may be slightly different from the real size of the display due to the presence of system bars or a status bar.

The code first retrieves the API level using Build.VERSION.SDK_INT. Then, it calls the appropriate method based on the API level:

  • For API level below 30, it uses displayMetrics to get the width and height in pixels.

  • For API level 30 and above, it uses getRealSize to get the real size of the display and getBounds to get the window bounds (optional).

The results are then displayed on a TextView in the activity layout.

Here's a table summarizing the three methods for getting the device screen size:

MethodDescriptionAvailable API Levels
DisplayMetricsGets general display information, including width and height in pixelsAll
realSizeGets the real size of the display without any window decor or compatibility scale factors30 and above
getBoundsGets the bounds of the window area30 and above

In summary, this code snippet provides a comprehensive way to get the device screen size in Kotlin, considering different API levels and potential discrepancies due to window decor or status bars.


MainActivity.kt

package com.example.jetpack

import android.app.Activity
import android.content.Context
import android.graphics.Point
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textView.text = "API Level ${Build.VERSION.SDK_INT}"

        val displayMetrics = displayMetrics()
        textView.append("\n\nUsing Display Metrics")
        textView.append("\n${displayMetrics.widthPixels} px * ")
        textView.append(" ${displayMetrics.heightPixels} px")

        realSize()?.apply {
            textView.append("\n\nUsing Real size")
            textView.append("\n$x px * $y px")
        }

        bounds()?.apply {
            textView.append("\n\nUsing Bounds")
            textView.append("\n${width()} px * ${height()} px")
        }
    }
}


// extension function to get display metrics instance
fun Activity.displayMetrics():DisplayMetrics{
    // display metrics is a structure describing general information
    // about a display, such as its size, density, and font scaling
    val displayMetrics = DisplayMetrics()

    if (Build.VERSION.SDK_INT >= 30){
        display?.apply {
            getRealMetrics(displayMetrics)
        }
    }else{
        // getMetrics() method was deprecated in api level 30
        windowManager.defaultDisplay.getMetrics(displayMetrics)
    }

    return displayMetrics
}


// extension function to get the real size of the display
fun Activity.realSize():Point?{
    return if (Build.VERSION.SDK_INT>=30){
        val realSize = Point()
        display?.apply {
            // gets the real size of the display without subtracting any
            // window decor or applying any compatibility scale factors
            getRealSize(realSize)
            return realSize
        }
        null
    }else{
        null
    }
}


// extension function to get window bounds
fun Activity.bounds():Rect?{
    return if (Build.VERSION.SDK_INT >=30){
        // returns the bounds of the area associated with
        // this window or visual context
        windowManager.currentWindowMetrics.bounds
    }else{
        null
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#EDEAE0">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="16dp"
        android:fontFamily="sans-serif-condensed-medium"
        tools:text="TextView"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials