Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error getting window size on android: "The method getWindowManager is undefined"

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;
like image 200
Harsan Valentin Avatar asked Jan 12 '12 10:01

Harsan Valentin


2 Answers

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

like image 165
oriolpons Avatar answered Oct 18 '22 18:10

oriolpons


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;
like image 31
Shreyash Mahajan Avatar answered Oct 18 '22 18:10

Shreyash Mahajan