Search code examples
androidandroid-animationandroid-orientationandroid-imagebuttonrotateanimation

Is there a way to animate setRotation or should it be replaced with a RotateAnimation?


I have made some buttons rotate accordingly to the device orientation using setRotation(). However, I have noticed this changes don't occur smoothly and I would like to know if there's a simple way to replace this method with a RotateAnimation. The main issue is that these orientation changes won't occur from the same angle, E.g. The animation will have to handle the rotation from 0-90 and from 270-90. I am using an OrientationEventListener to detect the angle orientation. Any ideas?

UPDATE:

   OrientationEventListener orientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_UI) {

    @Override 
    public void onOrientationChanged(int angle) {
        float currentAngle = downloadStatus.getRotation();
        if(angle > 260 && angle < 280) {
            downloadStatus.animate().rotationBy(90 - currentAngle).setDuration(100).start();
        } else if(angle > 80 && angle < 100) {
            downloadStatus.animate().rotationBy(-90 - currentAngle).setDuration(100).start();
        } else if(angle > 350 || angle < 10){
            downloadStatus.animate().rotationBy(-currentAngle).setDuration(100).start();
        } else if(angle > 170 && angle < 190){
            downloadStatus.animate().rotationBy(180 - currentAngle).setDuration(100).start();
        } 
    } 
}; 
orientationEventListener.enable();

What I tried next is replacing the reverse portrait angle if with the following two:

while (MyButtonCurrentAngle==90) { 
    if (ButtonsAngle > 170 && ButtonsAngle < 190) {
        MyButton.animate().rotationBy(90 - MyButtonCurrentAngle).setDuration(100).start();
    }
}
while (MyButtonCurrentAngle==270) { 
    if (ButtonsAngle > 170 && ButtonsAngle < 190) {
        MyButton.animate().rotationBy(-90 - MyButtonCurrentAngle).setDuration(100).start();
    }
}

Solution

  • Try updating my previous code to this:

        OrientationEventListener orientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_UI) {
    
            @Override
            public void onOrientationChanged(int angle) {
                float currentAngle = downloadStatus.getRotation();
                if(angle > 260 && angle < 280) {
                    downloadStatus.animate().rotationBy(90 - currentAngle).setDuration(100).start();
                } else if(angle > 80 && angle < 100) {
                    downloadStatus.animate().rotationBy(-90 - currentAngle).setDuration(100).start();
                } else if(angle > 350 || angle < 10){
                    downloadStatus.animate().rotationBy(-currentAngle).setDuration(100).start();
                }
            }
        };
        orientationEventListener.enable();