I can't play an animation with a Timer

526 views Asked by At

When I try to animate an image from a Timer I can't do it, however the Toast is executed. The animation works correctly because I tested from a button.It is rare, only the Toast runs and does not fail the application. Someone could help me!

public class Ayuda extends Activity {
        ImageView imagen_toro, imagen_vaca;
        Animation rotar;
        Timer timer;
        TimerTask timerTask;
        final Handler handler = new Handler();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_ayuda);

            imagen_toro = (ImageView) findViewById(R.id.imagen_toro_ayuda);
            imagen_vaca = (ImageView) findViewById(R.id.imagen_vaca_ayuda);
            rotar = AnimationUtils.loadAnimation(this, R.animator.animar_toro);

            timer = new Timer();
            timerTask = new TimerTask() {
                public void run() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            rotar.reset();
                            imagen_toro.setAnimation(rotar);
                            rotar.reset();
                            imagen_vaca.setAnimation(rotar);
                            int duration = Toast.LENGTH_SHORT;  
                            Toast toast = Toast.makeText(getApplicationContext(), "test", duration);
                            toast.show();
                        }
                    });
                }
            };
            timer.schedule(timerTask, 3000, 3000); //
        }   
    }
2

There are 2 answers

0
SacreDeveloper On BEST ANSWER

As a first, you should use PostDealyed instead of timer. also, you need to call start animation

        imageView.postDelayed(new Runnable() {

            @Override
            public void run() {
                imagen_toro.startAnimation(animation) 

            }
        }, 3000);
0
atok On

In general, using Timer is considered bad practice. Even Android documentation advises to use ScheduledThreadPoolExecutor in general case of running recurring tasks. Moreover, Android animations should be run using animation-specific APIs to avoid mistakes.

I suggest using rotar.setAnimationListener() to restart animation with imagen_vaca.startAnimation(rotar);

Also you should consider using new Animators API.