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 andgetBounds
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:
Method | Description | Available API Levels |
---|---|---|
DisplayMetrics | Gets general display information, including width and height in pixels | All |
realSize | Gets the real size of the display without any window decor or compatibility scale factors | 30 and above |
getBounds | Gets the bounds of the window area | 30 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.
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
}
}
<?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>
- android kotlin - Convert dp to pixels programmatically
- android kotlin - Get screen size from context
- android kotlin - RecyclerView animation
- android kotlin - RecyclerView smooth scroll
- android kotlin - Context menu example
- android kotlin - CalendarView get selected date
- android kotlin - Toolbar menu example
- android kotlin - Change indeterminate progress bar color
- android kotlin - Indeterminate ProgressBar example
- android kotlin - Change horizontal ProgressBar color
- android kotlin - ListView disable item programmatically
- android kotlin - ListView add header programmatically
- android kotlin - MaterialCardView border color width radius example
- android kotlin - Material button remove padding example
- android kotlin - AlertDialog single choice items example