Android – Get Screen Width and Height
In Android, WindowManager is available to every Activity. Through WindowManager, we can get the metrics of default display in which the activity is being shown.
In this tutorial, we will learn how to get width and height of the screen, on which the application is running, with the help of example Android Application.
Steps to Get Width and Height of Screen
To get Android screen width and height programmatically, follow these steps.
- Create a DispalyMetrics() object.
- Pass the displayMetrics object to getMetrics() method of Display class. WindowManager.defaultDisplay() returns the Display object.
- Screen Width could be obtained using displayMetrics.widthPixels
- Screen Height could be obtained using displayMetrics.heightPixels
In the following screenshot, width and height of the Android device screen is obtained programmatically and displayed using TextView.
Code – Get Width and Height
A quick snippet of the code to obtain screen dimensions programmatically is provided below
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
var width = displayMetrics.widthPixels
var height = displayMetrics.heightPixels
Example – Kotlin Android – Get Screen Dimensions Programmatically
In the following example, we shall obtain screen width and height, display it in the Activity with the help of TextView.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textV"
android:textSize="30px"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>
MainActivity.kt
package com.tutorialkart.drawshapeoncanvas
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.util.DisplayMetrics
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get device dimensions
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)
var width = displayMetrics.widthPixels
var height = displayMetrics.heightPixels
textV.text = width.toString() + " x " +height.toString()
}
}
Conclusion
In this Kotlin Android Tutorial – Get Screen Dimensions Programmatically, we have learnt to get screen width and height programmatically using DisplayMetrics.