Rotate andriod view with device orientation

Suson Thapa
2 min readApr 18, 2020
Photo by Mae Mu on Unsplash

I wanted to implement rotation of views like the stock camera app, when you rotate the phone, the buttons also rotate to match the orientation.

First we have to specify the orientation in the Android Manifest to prevent the android system from handling the orientation change itself.

Then initialize some variable to track the rotation degrees.

Then in onCreate() of activity or onCreateView() of fragment(which I would be using) initialize a OrientationEventListener and override onOrientationChanged. The key part is how to translate the orientation of the device to the view rotation. It took me sometime to figure that out.

The algorithm that I used above is working both on emulator and real device. The main issue is that the 0 and 360 degree is the same, so the orientation in android changes from 270 to 0 degree and needs extra checking for the conditions. Let me know in the comments below if you have got a better one.

Now the thing that remains to do is to implement the rotateButtons() function. Here is how I did it.

One thing to note is that, we need to reset the rotation to 0 degree when the rotation angle is 360 as I mentioned already. I tried to use ValueAnimator and reuse the same instance for performance issue, but it produced some issues with animation not being right. Instead I went with ObjectAnimator and AnimationSet to get the job done.

Here is how it looks.

Let me know in the comments below if you have any issues.

--

--

Suson Thapa

Android | iOS | Flutter | ReactNative — Passionate Software Engineer