Sunday, August 9, 2020

android kotlin - Get screen size programmatically

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>