Search code examples
androidmultithreadinganimationinvalidation

Android Animation Lags (what's the difference between two methods)


I want to animate a movement of images. I have two different implementations, the first involves two methods and runs smoothly, the other only needs one method and lags. I'd rather use the second one but can't figure out what causes the lags. I don't think it's the code that calculates the new positions since it's very simple and in both methods almost the same (I removed it for better readability)

Here is the first:

public void animateCircleMovement(final long duration) {

  // ...

  post(new Runnable() {
    @Override
    public void run() {
        animateStep();
    }
 });
}

public void animateStep() {

   // ...

  invalidate();
  if(curTime<endTime) {
    post(new Runnable() {
      @Override
      public void run() {
        animateStep();
      }
     });
  }
}

Here is the second

// ...
new Thread(new Runnable() {
  @Override
  public void run() {

  while(currTime<endTime){

  // ...

   postInvalidate();
 }
}).start();

Why does the second implementation cause lags?

Edited the postInvalidate() method


Solution

  • The animation runs smoothly if Thread.Sleep(10) is put into the while-loop.