7

I am really new to animations in android (and pretty much anything else). Is there a way to animate an ImageButton? I just want to rotate the button for sometimes. Thats all. Any help ?

Thanks.

Ahsan
  • 2,964
  • 11
  • 53
  • 96

2 Answers2

12

Try this code snippet.

rotate.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate

    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="0"
    android:duration="1000" />

</set>

in java file

ImageButton imgbt = (ImageButton)findViewById(R.id.your_id);
Animation ranim = (Animation)AnimationUtils.loadAnimation(context, R.anim.rotate);
imgbt.setAnimation(ranim);
Salim Mahboubi
  • 561
  • 7
  • 25
Niranj Patel
  • 32,980
  • 10
  • 97
  • 133
  • 1
    received an `java.lang.ClassCastException: android.view.animation.AnimationSet` error on this line : ` RotateAnimation ranim = (RotateAnimation)AnimationUtils.loadAnimation(this, R.anim.rotate);` – Ahsan Sep 27 '11 at 21:09
  • any help on this ? I am totally newbie with animations.. :( – Ahsan Sep 27 '11 at 21:10
  • 2
    I think the line should use Animation instead of RotateAnimation. – Ahsan Sep 27 '11 at 21:14
  • also, what to do if I want the cicrcular imagebutton to rotate around itself ? – Ahsan Sep 27 '11 at 21:16
  • this works fine if the padding for the imagebutton is uniform. thanks. – Ahsan Sep 27 '11 at 22:17
7

rotate.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:fromDegrees="0"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:startOffset="0"
    android:toDegrees="360" />

Java Code :

RotateAnimation rotateAnimation = (RotateAnimation) AnimationUtils.loadAnimation(context,R.anim.rotate);
view.startAnimation(rotateAnimation);
Sankar V
  • 4,794
  • 3
  • 38
  • 56