17

I need to get the window height and the weight.
I have this in my code:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
width1 = metrics.widthPixels; 
height1 = metrics.heightPixels;

but I have an error:

The method getWindowManager is undefined

what i should import for this? or i can get the sizes of the screed in different ways? i have imported

import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.content.Context;
import android.util.DisplayMetrics;
blahdiblah
  • 33,069
  • 21
  • 98
  • 152
Harsan Valentin
  • 213
  • 1
  • 2
  • 7

6 Answers6

49

Where are you using this code?

The error of the getWindowManager says that cannot find the method because the root of your class doesn't have it.

Try this:

((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(metrics);

or

((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
  .getDefaultDisplay().getMetrics(metrics);

If this doesn't work, please paste your activity

Shailendra Singh Rajawat
  • 8,172
  • 3
  • 35
  • 40
oriolpons
  • 1,883
  • 12
  • 20
5

Use this:

 display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
 display.getWidth(); // to get width of the screen
 display.getHeight(); // to get height of the Screen

UPDATE

Please review the Android-Developer site. For more reference.

You can use below snippet of code to fetch height-width of the device.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
halfer
  • 19,824
  • 17
  • 99
  • 186
Shreyash Mahajan
  • 23,386
  • 35
  • 116
  • 188
2

Use the Context of the activity with getActivityContext()

DisplayMetrics metrics = new DisplayMetrics();
getActivityContext().getWindowManager().getDefaultDisplay().getMetrics(metrics);
width1 = metrics.widthPixels; 
height1 = metrics.heightPixels;
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
1

You could use this for example if you are using it inside a fragment:

getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
Vas
  • 343
  • 4
  • 18
0

it works for me

import android.app.Activity;

((Activity)getContext()).getWindowManager().getDefaultDisplay().getMetrics(metrics);

mediaProjectionManager = (MediaProjectionManager)((Activity) getContext()).getSystemService(Context.MEDIA_PROJECTION_SERVICE);
Rkmr039
  • 175
  • 2
  • 6
0

Please check if you are calling above method in an activity class, or outside activity.

For Wallpaper, this method is not availed to you to get height or width of window, you need to get width and height of available window by using surface.

jeet
  • 29,001
  • 6
  • 52
  • 53