Gabby_987
Gabby_987

Reputation: 201

Animation delay android

I have three buttons, and i want them to randomly change color once I click the "Start" button. My problem is that I can't get the animations to show one after another and they end up running on top of each other.

I know that I have to use animationListiner() but I don't fully understand it and can't get it to work.

private void startColorAnimation(View v) {
for(int i =0; i<10;i++) {
            final int min = 0;
            final int max = 2;
            final int random = rnd.nextInt((max - min) + 1) + min;

            if(random == 0){
                animStart = 0xFFFF0000;
                animEnd = 0xFF990000;
                colorAnim = ObjectAnimator.ofInt(redButton, "backgroundColor", animStart, animEnd );
            }else if(random ==1){
                animStart = 0xFF3366FF;
                animEnd = 0xFF000099;
                colorAnim = ObjectAnimator.ofInt(blueButton, "backgroundColor", animStart, animEnd );
            }else if(random==2){
                animStart = 0xFF009900;
                animEnd = 0xFF66CC00;
                colorAnim = ObjectAnimator.ofInt(greenButton, "backgroundColor", animStart, animEnd );
            }
            colorAnim.setDuration(500);
            colorAnim.setEvaluator(new ArgbEvaluator());
            colorAnim.setRepeatCount(0);
            colorAnim.start();
        }
    }

Any kind of help would be appreciated.

Upvotes: 1

Views: 1003

Answers (1)

TrevJonez
TrevJonez

Reputation: 959

It looks like you intend to run a total of 10 animations randomly spread across the three buttons.

Because the duration the animation is set to 500ms you need to delay the next animation for the given button by at least 500ms.

The only way I can think of to accomplish this is to keep track of the pending/running animations and use the Handler.postDelayed(Runnable, delay) to time when you actually run the animation.

protected void randomizeTheButton(int animCount)
{
    int delay = 0;
    for(int i = 0; i < animCount; i++)
    {
        final ObjectAnimator colorAnim = ObjectAnimator.ofArgb(mButton, "backgroundColor", Color.argb(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
        colorAnim.setDuration(500);
        colorAnim.setEvaluator(new ArgbEvaluator());
        colorAnim.setRepeatCount(0);

        mHandler.postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                colorAnim.start();
            }
        }, delay);

        delay += colorAnim.getDuration();
    }
}

By calling this method in the button's click listener You get the following behavior. You would need to take this a step further than what I show here so that you can actually run different animations of different buttons.

animation example

Upvotes: 1

Related Questions