32

I have an ImageView on which I have applied a rotate animation. Since I want the rotation to go on continuously, I gave the repeatCount as infinite in my rotate.xml:

android:repeatCount="infinite"

In onCreate(), I load the animation and start it.

Animation myAnim    = AnimationUtils.loadAnimation(this, R.anim.rotate);
objectImg.startAnimation(myAnim); 

When a button is pressed, the rotation must stop. Hence in my onClick(), I called clearAnimation().

objectImg.startAnimation(myAnim); 

My simple question is whether stopping the animation is the right thing to do. I assume clearAnimation() corresponds to loadAnimation(), but there is no stopAnimation() that corresponds to startAnimation().

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
kiki
  • 13,627
  • 17
  • 49
  • 62

4 Answers4

73

Use clearAnimation() to stop an animation. There is no loadAnimation() on View.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Ok, thanks. So only startAnimation() and clearAnimation() are pplicable to views. – kiki Oct 12 '10 at 11:53
  • clearAnimation() didn't work for me, setAnimation(null) did – Leon Nov 09 '15 at 13:57
  • Hi @CommonsWare can u tell me how stop animation onClick of the view itself which is animating but not as a separate button? – Raghavendra Dec 15 '15 at 04:55
  • `img.clearAnimation()` is the best solution - `img.setAnimation(null)` also works, but it's less elegant - `img.startAnimation(null)` causes crash – voghDev Oct 27 '16 at 08:37
  • I had an infinite animation on an imageView of zoom in/zoom out. When I was trying to stop animation after clicking on view, neither anim.cancel() nor img.clearAnimation() works for me. Finally img.setAnimation(null) worked for me. – shaby Jan 13 '17 at 11:51
  • Working perfect – Daxesh V Feb 01 '20 at 11:21
39

You can also call anim.cancel(); but you should also call anim.reset(); immediately after it. Then when you want to start it again, just call startAnimation on the view.

duggu
  • 37,851
  • 12
  • 116
  • 113
John J Smith
  • 11,435
  • 9
  • 53
  • 72
  • 2
    animation.cancel(); requires API level 8, for stop the animation in API 7 and above the only option is view.clearAnimation(); – Toni Alvarez Dec 15 '12 at 02:12
  • 3
    `cancel()` would just reset the whole animation to initial state. But how to keep the last stopped state? – IgorGanapolsky Sep 28 '15 at 20:19
  • Proof of necessity to call anim.cancel() and anim.reset() together. https://developer.android.com/reference/android/view/animation/Animation.html#cancel() – VKostenc Mar 18 '19 at 12:55
-1

Simply add below two lines.

anim?.cancelAnimation()

anim?.progress = 0f
cigien
  • 57,834
  • 11
  • 73
  • 112
Prakash
  • 69
  • 7
-1

You can do it simply by removing this line : android:repeatCount="infinite" from your rotate.xml file

azaLiza
  • 37
  • 3