Search code examples
androidandroid-animationandroid-gui

Options for endlessly repeating function GUI calls while remaining responsive


I've got an animation to perform which consists of some arrow heads aligned horizontally where the alpha values of the arrows will change to achieve an animation effect (i.e. first arrow has alpha 1.0, then the second will get a value 1.0 etc.).

So if I have a function like this:

void highlightFirstArrow()
{
    mArrow1.setAlpha(1.0f);
    mArrow2.setAlpha(0.75f);
    mArrow3.setAlpha(0.50f);
    mArrow4.setAlpha(0.20f);
}

Then I'd want to start, repeat numerous times, then stop a function such as this:

void animateArrows()
    {
    highlightFirstArray();
    pause;
    highlightSecondArray();
    pause;
    etc.
    }

Obviously this would lock up the GUI thread if it were performed in a for look for example. What are the options for achieving the desired animiation:

- run a for loop in a separate thread 
- don't use a loop, instead constantly execute the functions individually via a timer
- use built in specific android animation mechanisms. If so which is most appropriate? Would AnimatorSet() be good for this scenario, or something else

Solution

  • You definitely shouldn't use any loops or timers. There're lots of built in classes which could help to animate your views. For instance you can use ValueAnimator:

    ValueAnimator.ofFloat(1f, 0.2f).setDuration(1000).addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override public void onAnimationUpdate(ValueAnimator animation) {
            float value = (float) animation.getAnimatedValue();
            arrow1.setAlpha(value);
            arrow2.setAlpha(value);
        }
    });