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

Questions:

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.

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.

Answer:

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

Answer:

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)
                windowManager.defaultDisplay.getRealSize(point)
            else windowManager.defaultDisplay.getSize(point)
            val screenWidth = point.x
            val screenHeight = point.y

docs:

https://developer.android.com/reference/android/view/Display.html#getRealSize(android.graphics.Point)

Answer:

This can be used in any class:

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

Hope this help

Answer:

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

object ScreenUtils {

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

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

}