Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I receiving an error when trying to use DisplayMetrics in Android?

Tags:

android

I'm just starting with Android programming, and I receive an error in the following code:

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);

The first line is fine according to Eclipse. But in the second line it's telling me that "getWindowManager"'s return type is missing. I don't understand this. When I search the internet on how to use this code, everyone is doing the same thing. Yet Eclipse is giving me an error.

like image 521
Charlie Avatar asked Jan 21 '23 15:01

Charlie


2 Answers

If this code is being used in a View instead of an Activity, you need to do something like

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

or

((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
  .getDefaultDisplay().getMetrics(dm);
like image 108
Ted Hopp Avatar answered Jan 23 '23 03:01

Ted Hopp


Providing more code would help people to help you debugging.

From your OP,

But in the second line it's telling me that "getWindowManager"'s return type is missing

getWindowManager is a method of Activity so make sure you have your code inside an activity (extends Activity))

like image 21
ccheneson Avatar answered Jan 23 '23 05:01

ccheneson