0

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!!

CodingChap
  • 1,088
  • 2
  • 10
  • 23
  • do you want explanation for the accepted solution of the question you are referring to? – Dinkar Kumar May 04 '21 at 06:28
  • Hi, my question is this: 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! – CodingChap May 04 '21 at 15:11

2 Answers2

0

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());
}
D_K
  • 152
  • 2
  • 9
0
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