Issue
I have a container (GridLayout) in which I place multiple views. When I click on any of these views, an infinite animation should be applied (to indicate that it's the selected/chosen view).
The problem is that I need to clear the previous animation so there's only one animation playing at a time (for the view that's clicked).
I was thinking to have a global definition of animation and then simply cancel it onClick and assign a new View to it, but the ObjectAnimator has no method to cancel it.
GridLayout container = (GridLayout) filterPackContainer.findViewById( R.id.container );
for( int f=0; f<10; f++ )
{
View child = that.getLayoutInflater().inflate( R.layout.child, null );
child.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
ObjectAnimator anim = ObjectAnimator.ofFloat( v, "alpha", .5f, 1f );
anim.setDuration( 1000 );
anim.setRepeatMode( 2 );
anim.setRepeatCount( 999999 );
anim.start();
}
});
container.addView( child );
}
Then I tried to save the View as reference inClick, and cancel any existing animations using clearAnimation(), but this has no effect and the animation just keeps playing.
View vRef = null;
---------------------
GridLayout container = (GridLayout) filterPackContainer.findViewById( R.id.container );
for( int f=0; f<10; f++ )
{
View child = that.getLayoutInflater().inflate( R.layout.child, null );
child.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if( vRef != null )
vRef.clearAnimation();
vRef = v;
ObjectAnimator anim = ObjectAnimator.ofFloat( v, "alpha", .5f, 1f );
anim.setDuration( 1000 );
anim.setRepeatMode( 2 );
anim.setRepeatCount( 999999 );
anim.start();
}
});
container.addView( child );
}
any hints on how to handle this properly? Thanks!
Solution
You can use AnimatorSet to control your animations.
This class plays a set of Animator objects in the specified order. Animations can be set up to play together, in sequence, or after a specified delay.
There are two different approaches to adding animations to a AnimatorSet: either the playTogether() or playSequentially() methods can be called to add a set of animations all at once, or the play(Animator) can be used in conjunction with methods in the Builder class to add animations one by one.
AnimatorSet animatorSet = new AnimatorSet();
child.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
if(animatorSet.isRunning)
animatorSet.cancel();
ObjectAnimator anim = ObjectAnimator.ofFloat( v, "alpha", .5f, 1f );
anim.setDuration( 1000 );
anim.setRepeatMode( 2 );
anim.setRepeatCount( 999999 );
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(anim);
animatorSet.start();
}
});
Answered By - Mayank Bhatnagar
Answer Checked By - Cary Denson (JavaFixing Admin)