Android – Rotate an Imagewith Animation

androidandroid-animationandroid-imageviewimage-rotation

The two states of the image

What I Have

I have an arrow image (like the left one). When the user clicks on it, it should rotate 180 degree with an animation and should look like the right one.

What I Have Done

private void rotate(float degree, final int toggleV) {

        final RotateAnimation rotateAnim = new RotateAnimation(0.0f, degree,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);

        rotateAnim.setDuration(500);
        toggle.startAnimation(rotateAnim);
        rotateAnim.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {


                if (toggleV == 1)
                    toggle.setImageResource(R.drawable.toggle_up);
                else
                    toggle.setImageResource(R.drawable.toggle_down);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

The Problem

I see that the animation works fine but there is a little flicker while setting the image. May be because of the time difference when the animation ends and the image is set.

How can I remove this flicker issue? Do you have any better approach to do this?

Best Solution

First of all, what is you minimum SDK requirement? In case it's at least Android 3.0, you can use the newer animation framework, and animate your Image with something like this:

imageView.animate().rotation(180).start();

About the flicker: I wouldn't reset the source image of the ImageView after the rotation, I'd just leave in the original and make sure that the rotation animation fills after the animation, leaving the image rotated. The flicker is most likely caused by the View's relayout/redraw upon changing the source image.

Further visual artifacts (flicker?) may be caused because the original-rotated image and the rotated static image might differ in a few pixels.

Related Question