Search code examples
androidonclickimagebuttonobjectanimator

How to stop imagebutton at current position when clicked during animation?


I have an ImageButton which moves down from the top of the screen. The image animates while moving down to the screen. I want to make it stop WHEREVER and WHENEVER it is clicked on. Basically if the image is clicked in the middle of the animation, I want to it to stop at that current position. My progress can be seen in the code block below, the code makes the image animate and move from top to bottom, when the image is clicked, the image moves straight to the desired position (500), instead of stopping at the current position. Please be really descriptive as I am a beginner in programming. Thank you.

    final ImageButton image = (ImageButton)findViewById(R.id.image);
    final ObjectAnimator objectAnimator= ObjectAnimator.ofFloat(image, View.TRANSLATION_Y, 0, 500); //where the image should move to
    objectAnimator.setStartDelay(2000); //how long to wait before starting
    objectAnimator.setDuration(2000);   //how long animation lasts
    objectAnimator.start();


    image.setOnClickListener(
            new ImageButton.OnClickListener() {
                public void onClick(View v) {
                    image.setTranslationY(image.getY()); //gets current position of Y?
                    objectAnimator.end(); //ends the animation

                }
            }
    );

Solution

  • From the documentation of ValueAnimator#cancel it seems that

    objectAnimator.cancel();
    

    should solve your problem.