java – How to get screen dimensions in Android?

Question:

I am trying to get the screen dimensions of an Android device, I am trying with this code:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // obsoleto (deprecated)
int height = display.getHeight();  // obsoleto (deprecated)

Which is obsolete (deprecated), what would be the current correct way to obtain the dimensions of the device screen?

Answer:

You can use DisplayMetrics

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels; // ancho absoluto en pixels 
int height = metrics.heightPixels; // alto absoluto en pixels 

Note: This form is supported from API Level 1

Scroll to Top
AllEscort