Getting screen size not from Activity subclass

I have a subclass of the kind that starts with an activity subclass like this:

this.setContentView(instanceOfMyView); 

In this subclass of view, I want to do some work with the screen size, but all the people here say that it needs to be run, for example:

 DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); screenWidth = dm.widthPixels; screenHeight = dm.heightPixels; 

But getWindowManager() is a method that can only be called from an activity subclass (am I right?)

So this is a bad idea, and do I need to get the screen size in action and use it as parameters in the view constructor, or is there a way to get the screen size in a view subclass? Maybe you just need to somehow get a link to an instance of the activity in the view class?

Thanks in advance.

+6
source share
2 answers

Yes, there is a way, if you can pass a context object to your inactivity class,

  int width= context.getResources().getDisplayMetrics().widthPixels; int height= context.getResources().getDisplayMetrics().heightPixels; 

You do not need the Activity object itself.

+25
source
 DisplayMetrics metrics = getBaseContext().getResources().getDisplayMetrics(); final int w = metrics.widthPixels; final int h = metrics.heightPixels; 
+4
source

Source: https://habr.com/ru/post/921404/


All Articles