Search code examples
androidimageviewandroid-imageviewvisibility

Making Imageview disappear After Animation


I have a method that creates an animation for an ImageView object with specified parameters:

public void animateMove(float x, float y, int milsecs)
{
    float origX = view.getX();
    float origY = view.getY();

    view.setVisibility(View.VISIBLE);

    Path linePath = new Path();
    linePath.lineTo(x, y);

    ObjectAnimator anim = ObjectAnimator.ofFloat(view, "translationX", "translationY", linePath);
    anim.setDuration(milsecs);
    anim.start();

    view.setVisibility(View.INVISIBLE); // this code is the problem
    view.setX(origX);
    view.setY(origY);

}

However, when I call the setVisibility method to make the ImageView invisible, it runs at the same time as when the animation is occurring and so nothing can actually be seen. If I remove this piece of code, I can see the animation of the view just fine.

How can I have this method create an animation and turns it invisible only AFTER the whole animation is complete?


Solution

  • Add this to your code before anim.start():

    anim.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }
    
            @Override
            public void onAnimationEnd(Animator animation) {
                        view.setVisibility(View.INVISIBLE);
                        view.setX(origX);
                        view.setY(origY);
            }
    
            @Override
            public void onAnimationCancel(Animator animation) {
            }
    
            @Override
            public void onAnimationRepeat(Animator animation) {
            }
    });