Skip to content
Advertisement

Java Android ImageView-Image rotation only works for the first time

I have written a code on in java for image view that will rotate and fade away and another image will be visible, I use imageViewer.animate.rotation(3600).alpha(0); now this works fine when I run the code on an emulator, the images fade and re-appear just fine, but the problem is about the rotation after I compile the app for the first time when I click on the image, it will rotate and fade away and the next picture is shown, but when I tap on the image again, it will not rotate, instead only the fade in and fade out will work but not the rotation (Note that it rotates for the first time after compilation but then doesn’t rotates and fade in/out works only). Here is the code:

public class MainActivity extends AppCompatActivity
{
    boolean eggview = true;

    public void fade(View view)
    {
        ImageView eggImageView = (ImageView) findViewById(R.id.egg);
        ImageView chickImageView = (ImageView) findViewById(R.id.chick);
        if (eggview)
        {
            eggview = false;
            eggImageView.animate().rotation(3600).setDuration(1200).alpha(0);
            chickImageView.animate().alpha(1);
        }
        else
        {
            eggview = true;
            chickImageView.animate().rotation(3600).alpha(0).setDuration(1200);
            eggImageView.animate().alpha(1);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Advertisement

Answer

You have to set rotation to 0 when setting alpha to 1. When You set rotation to 3600 it isn’t 3600 degrees from the current state but from the default state, that’s why it works only one time.

boolean eggview = true;
public void fade(View view)
{
    ImageView eggImageView = (ImageView) findViewById(R.id.egg);
    ImageView chickImageView = (ImageView) findViewById(R.id.chick);
    if (eggview)
    {
        eggview = false;
        eggImageView.animate().rotation(3600).setDuration(1200).alpha(0);
        chickImageView.animate().alpha(1).rotation(0);
    }
    else
    {
        eggview = true;
        chickImageView.animate().rotation(3600).alpha(0).setDuration(1200);
        eggImageView.animate().alpha(1).rotation(0);
    }
}

If You don’t want to make a backward rotation when fading in just set rotation to actual state + 3600. But the main problem with Your code is setting rotation to the actual state.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement