I want to get the phone orientation but keep the screen orientation to portrait. So no matter the user turns the phone to landscape or portrait, the view stays the same, but I can get whether it is turned to landscape or portrait.
Setting the activity to android:screenOrientation="portrait" will fix both but I wouldn't be able to detect the phone orientation via
public void onConfigurationChanged(Configuration newConfig) {
switch (newConfig.orientation) {
case Configuration.ORIENTATION_PORTRAIT:
Toast.makeText(this, "Portrait", Toast.LENGTH_SHORT).show();
break;
case Configuration.ORIENTATION_LANDSCAPE:
Toast.makeText(this, "Landscape", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
Has anyone an idea how to fix that?
I needed a solution that would give me the orientation only on-demand. This one worked for me:
If you disable screen orientation change then obviously the onConfigurationChanged will never be called...
I think the only way is to use accelerometer sensor, check this link.
In case anybody is looking for a Webview/javascript solution to the question, the below can do that.
This will trigger custom 'flip' events on the window, with 'extra parameters' as jquery has them. It also sets window.flip, analogue to window.orientation:
The jquery is not really needed. I had it required anyway.
Could you satisfy your requirement with the accelerometer? If so, perhaps something like this (untested) fragment would suit your purposes.
Here is a multi-purpose class for easily managing screen orientation changes:
This is way more simple, reusable, and you can also get REVERSE_LANDSCAPE and REVERSE_PORTRAIT orientations.
You must implement OrientationListener in order to get notified only when an orientation change occurs.
Don't forget to call orientationManager.enable() to begin orientation tracking, and then calling orientationManager.disable() (this two methods are inherited from OrientationEventListener class)
UPDATE: use case example
To get into that you want to set in manifest file in that activity
Then when user rotate phone it will came into public void onConfigurationChanged() method. Also remove
from the same activity.