Android | Getting screen height as width and screen width as height

扶醉桌前 提交于 2019-12-12 03:36:08

问题


I have the following piece of code in my app to get screen width and height:

screenHeight = (short) Activity.getWindow().getWindowManager().getDefaultDisplay().getHeight();
screenWidth  = (short) Activity.getWindow().getWindowManager().getDefaultDisplay().getWidth();

And in the AndroidManifest, I have:

 <activity
      android:name="com.test.MyActivity"
      android:configChanges="keyboardHidden|orientation"
      android:launchMode="singleTask"
      android:screenOrientation="landscape"
      android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
 </activity> 

Now, for a device with screen resolution 1280x700, I expect the screenWidth variable to always have the value 1280 and the screenHeight to be 700. This is regardless of how the user may be holding the phone.

But still, sometimes I get screenWidth equal to 700 and height equal to 1280. Why is that? Shouldn't my manifest file enforce the orientation of my app to always remain landscape?


回答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
    ...



回答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.




回答3:


put the line in your manifest activity tag

android:configChanges="keyboardHidden|orientation"

override the method in your activity

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

and put the line in onCreate() method

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAP);

your application will remain in landscap only. :)



来源:https://stackoverflow.com/questions/14999427/android-getting-screen-height-as-width-and-screen-width-as-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!