javaandroidandroid-touch-event

How to limit or disble clicks/touch events for a specific amount of time in android?


I have an app where I animate some views on click.

However while the animation is going on it's still possible to initiate other on click events, which in the end cause multiple problems with the animations. I would need to make it so that no new animation starts while a certain one is going on.

Let's say the animation shuffles clickable views on screen. How do I make it so that the user can't initiate a new click command for x amount of time, where x could be the duration of the animation, or some other solution with similar results.

I'm just not even sure what I'm looking for when it comes to terminology. What areas should I look into to manipulate user inputs like this? Any good source on the topic would also be welcome.


Solution

  • You can always disable the click event with a flag and enable it again when the animation has finished. It isn't a perfect solution, but it does the trick quite well in most cases.

    For example, if you are using an Animator for your animation, you can do something like this:

    private boolean isClickEnabled = true;
    
    ...
    
    @Override
    public synchronized void onClick(View v) {
        if (isClickEnabled) {
            // We disable the click, which will be enabled again when the animation ends
            isClickEnabled = false;
    
            ...
    
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    // We enable the click again now that the animation has finished
                    isClickEnabled = true;
                }
            });
            animator.start();
        }
    }
    

    The same applies for when you use the Animation class, but with the AnimationListener instead.

    Please note that, instead of saving a local boolean, you could just disable and enable the click on the view using view.setClickable(true/false) – it really depends on what you need and on your implementation, but the basic idea remains the same.