Home » Android » android – Getting screen size not from Activity subclass

android – Getting screen size not from Activity subclass

Posted by: admin June 15, 2020 Leave a comment


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


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();
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.

How to&Answers:

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.


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


The other answers here won’t give you the screen resolution.

Here’s how you should do it:

            val windowManager=context.getSystemService(WINDOW_SERVICE) as WindowManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
            else windowManager.defaultDisplay.getSize(point)
            val screenWidth = point.x
            val screenHeight = point.y




This can be used in any class:

DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
Integer with = metrics.widthPixels;
Integer height = metrics.heightPixels;

Hope this help


Even simpler than accepted answer. You don’t need context.

object ScreenUtils {

    fun getScreenWidth() = Resources.getSystem().displayMetrics.widthPixels

    fun getScreenHeight() = Resources.getSystem().displayMetrics.heightPixels