How can you display screen size in Android Studio(simple way)?

384 views Asked by At

I'm trying to display the screen width and height to logcat.

I have seen this stack overflow post: Getting screen width on API Level 30 (Android 11): getDefaultDisplay() and getMetrics() are now deprecated. What should we use instead?

But the accepted solution is confusing and complicated for someone like me new to DisplayMetrics and Display in Android Studio.

Currently, I know how to do it this way:

public class ScreenUtility {
    private Activity activity;
    private Float dpHeight, dpWidth;

    public ScreenUtility(Activity activity) {
        this.activity = activity;

        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();

        display.getMetrics(displayMetrics);
        float density = activity.getResources().getDisplayMetrics().density;

        dpHeight = displayMetrics.heightPixels / density;
        dpHeight = displayMetrics.widthPixels / density;

    }


    public Float getDpHeight() {
        return dpHeight;
    }

    public Float getDpWidth() {
        return dpWidth;
    }
}

However, .getMetrics is deprecated. As a result, the code returns the width and heigh as null.

  1. (I am watching an older video on these concepts)Is there any way I can change this code and adjust my knowledge to the modern methods of Display and DisplayMetrics?

  2. How are DisplayMetrics and Display different? In the docs, it describes them as both tools that provide the size of a Display. Or is DisplayMetrics used as a parameter for Display?

Thanks!!

2

There are 2 answers

3
D_K On

This is how you can display height and width of the screen

try{
    DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int height = displayMetrics.heightPixels;
            int width = displayMetrics.widthPixels;

    Log.e("test","Height : " + height + " width : " + width);
}
catch(Exception e){
Log.e("test","exception : " + e.toString());
}
0
Muhammed naseef Koppilakkal On
val windowMetrics = requireActivity().windowManager.currentWindowMetrics
val displayMetrics = resources.displayMetrics

val pxHeight = windowMetrics.bounds.height()
val pxWidth  = windowMetrics.bounds.width()

val density  = displayMetrics.density

val dpHeight = pxHeight/density
val dpWidth  = pxWidth/density