So I want my app to always lock onto the natural orientation of the device. So basically, I want to force the rotation to 0 degrees. There's a getRotation()
method here:
http://developer.android.com/reference/android/view/Display.html
However, there is no setRotation(int rotation) that would accept one of the Surface.ROTATION_X
parameters found here:
http://developer.android.com/reference/android/view/Surface.html
So, is there some way to do this with a single line of code that will always work? Or would this have to be done with some code?
The only thing I can think of as a manual solution is the following, but I have some concerns about it.
I can use the display.getRotation()
. Then I'll check if it's 0 or 180 degrees, after that I'll get the display height and width, and see which one is longer than the other. If it appears I'm in landscape mode, then I'll know that the device's natural orientation is landscape so I could set it to landscape. However if the rotation was 270 or 90, then I would know the natural orientation is portrait, and I could set it to portrait.
However, my concern is where to do this such that it always works. Let's say the user is rotating the screen as this piece of code is executing, if the device changes orientation in between the time I use the getRotation()
method, and check the width against the height with some if statements and what not, I think it could throw everything off. What happens if I put this in onCreate()
or onResume()
? Is it possible that things can get out of wack?
Is it possible for a the onCreate()
or onResume()
to be interrupted by a screen re-orientation due to the user turn the开发者_运维技巧 device around? The other issue is that if you flip the device by 180 degrees, the activity is never destroyed, so I think the behavior of this situation could very whether it's a 90 degree turn, or a 180 degree turn.
You can "set" the screen orientation in the manifest. See here: http://developer.android.com/guide/topics/manifest/activity-element.html#screen
<activity
android:name=".Activity"
android:screenOrientation="portrait"
android:theme="@style/Theme.D1"
android:label="@string/title_activity"/>
The value you're probably looking for is; "user" The user's current preferred orientation. However, I would test this on several test cases to be sure. HTH!
精彩评论