Android Kotlin: How to programmatically get device screen density

This code demonstrates how to programmatically get the device's screen density in Kotlin for an Android application.

The code defines an extension property for the Activity class named displayMetrics. This property retrieves an instance of the DisplayMetrics class, which provides information about the display, such as its size, density, and font scaling.

The displayMetrics property uses a conditional statement to check the Android API level. If the API level is 30 or higher, it uses the getRealMetrics method to get the display metrics. Otherwise, it uses the deprecated getMetrics method.

The code then retrieves the following three values from the DisplayMetrics instance and displays them on the screen using a TextView:

  • Logical density: This is a scaling factor that indicates the ratio between pixels and dp (density-independent pixels). A dp value of 1 corresponds to 1 logical pixel on a reference display with a 160 dpi density.
  • Density DPI: This is the number of dots per inch (dpi) of the screen.
  • Scaled density: This is a scaling factor for fonts displayed on the screen. It is based on the logical density and the font scaling factor set by the user.

In summary, this code provides a way to programmatically access the device's screen density information in an Android application.

Here is a table summarizing the different properties retrieved from the DisplayMetrics class:

PropertyDescription
densityLogical density of the display
densityDpiScreen density expressed as dots-per-inch (dpi)
scaledDensityScaling factor for fonts displayed on the display


MainActivity.kt

package com.example.jetpack

import android.app.Activity
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)

        // the logical density of the display
        textView.text = "Screen Density : ${displayMetrics.density}"

        // the screen density expressed as dots-per-inch
        textView.append("\n\nDensity DPI : ${displayMetrics.densityDpi}")

        // a scaling factor for fonts displayed on the display
        textView.append("\nScaled Density : ${displayMetrics.scaledDensity}")
    }
}


// extension property to get display metrics instance
val Activity.displayMetrics: DisplayMetrics
    get() {
        // 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
    }

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="#E5E4E2">

    <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"
        tools:text="TextView"
        android:fontFamily="sans-serif-condensed"
        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