Search code examples
androidandroid-activityandroid-viewscreen-size

Getting screen size not from Activity subclass


I have a view subclass that starts from activity subclass like that:

this.setContentView(instanceOfMyView);

In that my view subclass I want to make some work with screen size, but all people here says that it should be started like:

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

But getWindowManager() is the method that can be called from activity subclass only (Am I right?)

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

Thanks in advance.


Solution

  • Yes there is a way, if you can pass the Context Object to your non activity class,

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

    You don't need the Activity Object itself.