Skip to content Skip to sidebar Skip to footer

Android | Getting Screen Height As Width And Screen Width As Height

I have the following piece of code in my app to get screen width and height: screenHeight = (short) Activity.getWindow().getWindowManager().getDefaultDisplay().getHeight(); screen

Solution 1:

android:screenOrientation="landscape"

this is causing the issue here , If you have to solve your issue then make it to portrait.

And if you do not want to restrict yourself then check the orientation in code and use the your code further.

Not the code but an idea, e.g.

if(getOrientation=="portrait")

   determine height and width.

 else
    ...

Solution 2:

It's a somewhat tricky part of Android. You should not rely on such methods due to numerous things which can happen asynchronously in you app. If your app is forced to run in landscape orientation, but you have a regular phone, which probably has portrait as the default orientation for home and lock screen, you're in trouble. Every time you lock the screen or start a new instance of your app, you cannot be sure if the reported width and height are in landscape or portrait orientation due to rotation animation pending.

To determine the resolution properly you have to find out, which orientation you're actually checking. You can use accelerometer, OrientationEventListener, OnConfigurationChanged and rootView size. Still, I guess the best way of dealing with this problem is to just swap width and height in your code, so the width is always the bigger value. Just like that.

Solution 3:

put the line in your manifest activity tag

android:configChanges="keyboardHidden|orientation"

override the method in your activity

@OverridepublicvoidonConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

and put the line in onCreate() method

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAP);

your application will remain in landscap only. :)

Post a Comment for "Android | Getting Screen Height As Width And Screen Width As Height"