Utility Class to Get Screen Width & Height in Kotlin Android

It’s a common requirement to get screen width or height for Android developers in their Apps. In this article, I am sharing a simple utility class that will help you to get screen width & height in Kotlin Android. Just copy and paste the following utility class in your Kotlin project and it will get screen size & dimensions and return it back to you.

Get Screen Size in Kotlin Android

Utility Class to Get Screen Dimensions (Width & Height)

Create a new Kotlin file in your project with name ScreenUtils.kt and copy and paste the following class code in that file.

package com.example.handyopinion

import android.app.Activity
import android.util.DisplayMetrics

class ScreenUtils {

    fun getScreenWidth(activity: Activity): Int {
        val displayMetrics = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(displayMetrics)
        return displayMetrics.widthPixels
    }

    fun getScreenHeight(activity: Activity): Int {
        val displayMetrics = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(displayMetrics)
        return displayMetrics.heightPixels
    }
}

As you can see in the above code, In this class we have 2 methods, getScreenWidth(activity: Activity) & getScreenHeight(activity: Activity). Both methods take the Activity object as a parameter and use WindowManager & DisplayMetrics interfaces to get the screen dimensions.

How to Use ScreenUtils Class

val screenUtils = ScreenUtils();
val height = screenUtils.getScreenHeight(this);
val width = screenUtils.getScreenWidth(this);

Thats it. This how you can get get screen width & height in Kotlin Android 🙂

If you have any question, Feel free to ask in comments section below.

Next: Pick Image From Gallery in Kotlin – Android

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: