1

I'm experimenting with SurfaceView and creating simple animations with it, I don't understand why my animation (changins screen color from black to white) is working here (without using SurfaceHolder.Callback)

public class MySurface extends SurfaceView {
   private boolean playing = true;
   private int counter = 0;

   public MySurface(Context context){
       super(context);
       new Anim().start();
   }

   private class Anim extends Thread {
       @Override
       public void run() {
           while (playing) {
               try {
                   sleep(1000);
                   draw();
                   counter++;
               } catch (Exception e){
                   e.printStackTrace();
               }
           }
          }

       private void draw() {
           SurfaceHolder holder = getHolder();
           Canvas canvas = holder.lockCanvas();
           if (canvas != null) {
               if (counter % 2 == 0) {
                   canvas.drawColor(Color.WHITE);
               } else
                   canvas.drawColor(Color.BLACK);
               holder.unlockCanvasAndPost(canvas);
           }
       }
   }
}

But it's not working here, what's the difference? I think it might be caused by calling .run() instead of .start()

public class MySurface extends SurfaceView implements SurfaceHolder.Callback {
   Anim anim;
   private boolean playing = true;
   private int counter = 0;

   public MySurface(Context context){
       super(context);
   }
   // all Callbacks are overrided i didn add them to make code easier to read
   @Override
   public void surfaceCreated(SurfaceHolder surfaceHolder) {
       anim = new Anim();
       anim.run();
   } 


   private class Anim extends Thread {
       @Override
       public void run() {
           while (playing) {
               try {
                   sleep(1000);
                   draw();
                   counter++;
               } catch (Exception e){
                   e.printStackTrace();
               }
           }
       }

       private void draw() {
           SurfaceHolder holder = getHolder();
           Canvas canvas = holder.lockCanvas();
           if (canvas != null) {
                if (counter % 2 == 0) {
                    canvas.drawColor(Color.WHITE);
               } else
                   canvas.drawColor(Color.BLACK);
               holder.unlockCanvasAndPost(canvas);
           }
       }
    }
}

EDIT: I forgot to add getHolder().addCallback(this) that caused the issue.

Could someone still point out the differnces between those two methods and tell which one is better?

EDIT2: anim.start() was also needed

leedwon
  • 142
  • 1
  • 9

0 Answers0