-1

in the MainActivity class the following code works fine to get screen size

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;

I wanted to get the width and height in my onDraw method so if the user rotates the device the method would see the new values

so I copied the code into my onDraw method.

I get a error saying:

getWindowManager() is undefined

I'm assuming this because the onDraw method is in a different class si it does not have that method.

Is there a way to get the screen size in the onDraw method?

Cœur
  • 34,719
  • 24
  • 185
  • 251
Ted pottel
  • 6,721
  • 19
  • 72
  • 130
  • 1
    Possible duplicate of [Get Screen width and height](https://stackoverflow.com/questions/4743116/get-screen-width-and-height) – petey Jul 17 '17 at 17:02
  • What class's `onDraw()` are you putting this into? That makes a difference. In general you should probably override `onMeasure()` if you are making a custom view? – Richard Le Mesurier Jul 17 '17 at 17:03
  • where does onDraw() method belong to? fragment or activity? – Jay Jul 17 '17 at 17:15

1 Answers1

1

As you've guessed, getWindowManager() is a method of Activity, not View, so you cannot call it from your onDraw() implementation.

However, there are other ways to get a WindowManager instance. Below code will work, though in general allocating objects inside onDraw() is not recommended.

@Override
public void onDraw(Canvas canvas) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    WindowManager manager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
    manager.getDefaultDisplay().getMetrics(displayMetrics);
    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels;
}
Ben P.
  • 49,703
  • 5
  • 81
  • 113