I am trying to detect the device orientation changes with an OrientationEventListener, so I can make some buttons rotate with the device orientation, while the layouts are set to portrait. I was wondering if it would be a better idea to do this with a SensorEventListener, but I can't figure out how to do it as I have never worked with sensors before. Is there any way to do this?
Asked
Active
Viewed 151 times
1 Answers
4
OrientationEventListener is the right way to go. Why do you think SensorEventListener is better?
Do something like this:
OrientationEventListener orientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_UI) {
@Override
public void onOrientationChanged(int angle) {
if(angle > 260 && angle < 280) {
button.setRotation(90);
} else if(angle > 80 && angle < 100) {
button.setRotation(270);
} else if(angle > 350 || angle < 10){
button.setRotation(0);
}
}
};
orientationEventListener.enable();

Xiaoyu Yu
- 725
- 3
- 12
-
I though that an OrientationEventListener would always detect portrait. Besides, http://stackoverflow.com/questions/9021890/get-phone-orientation-but-fix-screen-orientation-to-portrait. – Lekstadt Nov 01 '15 at 02:11
-
1I've done very similar things with OrientationEventListener, and it totally works. It will detect the angle of your device, which is more flexible. In your link the person was overriding onConfigurationChanged and obviously it won't work. – Xiaoyu Yu Nov 01 '15 at 02:23
-
That's great, that's totally what I wanted to do. To detect the angle of the device and rotate the buttons accordingly, do you have some example that could guide me? – Lekstadt Nov 01 '15 at 02:42
-
1I edited the answer, note that the angle definition in onOrientationChanged and setRotation are different, so the code looks kind of confusing. You could read the docs. – Xiaoyu Yu Nov 01 '15 at 05:16