Search code examples
androidimageviewrotateanimation

Rotate imageview stuck


I want to create a simple image which rotates 20 degrees (like clock) and 20 degrees back. I have this simple layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/witewall_3">

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/pet"
        android:src="@drawable/animal"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

and this activity

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ImageView image=(ImageView) findViewById(R.id.pet);

        RotateAnimation anim = new RotateAnimation(0f, 0f, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);

        anim.setInterpolator(new LinearInterpolator());
        anim.setRepeatCount(Animation.INFINITE);
        anim.setDuration(700);

        image.startAnimation(anim);
    }
}

what am I doing wrong and my image is not rotating? i've tried a lot of tutorials and nothink worked :(


Solution

  • You are rotating from 0 to 0 degrees. The first parameter is the from degrees and the second parameter of the RotationAnimation class is the ending point degrees.

    RotateAnimation anim = new RotateAnimation(0f, 20f, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
    

    If you want to continue to rotate by twenty you also need to provide the first parameter which is the degrees from which it will animate.

    RotateAnimation anim = new RotateAnimation(20f, 40f, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
    RotateAnimation anim = new RotateAnimation(40f, 60f, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);