Skip to content Skip to sidebar Skip to footer

Animating Button Presses / Clicks In Android

I'm trying to create a button-click animation, e.g. the button scales down a little when you press it, scales back up when you release. If you simply tap, you get the press and rel

Solution 1:

I built a sample Button class that buffers animations and executes them in a queue according to what you need:

publicclassAnimationButtonextendsButton 
{
    private List<Animation> mAnimationBuffer = newArrayList<Animation>();;
    privateboolean mIsAnimating;

    publicAnimationButton(Context context) 
    {
        super(context);

    }

    publicAnimationButton(Context context, AttributeSet attrs) 
    {
        super(context, attrs);

    }

    publicAnimationButton(Context context, AttributeSet attrs, int defStyle) 
    {
        super(context, attrs, defStyle);

    }


    @OverridepublicbooleanonTouchEvent(MotionEvent event) 
    {
        if (event.getAction() == MotionEvent.ACTION_DOWN)
        {
            generateAnimation(1, 0.75f);
            triggerNextAnimation();
        }
        elseif (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP)
        {
            generateAnimation(0.75f, 1);
            triggerNextAnimation();
        }

        returnsuper.onTouchEvent(event);
    }

    privatevoidgenerateAnimation(float from, float to)
    {
        ScaleAnimationscaleAnimation=newScaleAnimation(from, to, from, to);
        scaleAnimation.setFillAfter(true);
        scaleAnimation.setDuration(500);
        scaleAnimation.setAnimationListener(newScaleAnimation.AnimationListener() 
        {       
            @OverridepublicvoidonAnimationStart(Animation animation) { }

            @OverridepublicvoidonAnimationRepeat(Animation animation) { }

            @OverridepublicvoidonAnimationEnd(Animation animation) 
            {               
                mIsAnimating = false;
                triggerNextAnimation();
            }
        });

        mAnimationBuffer.add(scaleAnimation);
    }

    privatevoidtriggerNextAnimation()
    {
        if (mAnimationBuffer.size() > 0 && !mIsAnimating)
        {
            mIsAnimating = true;
            AnimationcurrAnimation= mAnimationBuffer.get(0);
            mAnimationBuffer.remove(0);

            startAnimation(currAnimation);
        }
    }

}

Hope this helps :)

Solution 2:

Looks like L Preview adds the ability to specify animations for state changes in the xml file.

https://developer.android.com/preview/material/animations.html#viewstate

Post a Comment for "Animating Button Presses / Clicks In Android"