Android中的动画按钮按下/点击

时间:2013-10-09 01:36:59

标签: android animation user-interface

我正在尝试创建按钮点击动画,例如按下按钮时按钮会缩小一点,释放时按钮会向上缩放。如果您只是点击,就可以将按下和释放连接在一起。

我设置了一个onTouchListener和一些XML定义的AnimatorSets,一个用于印刷机,一个用于发布。在ACTION_DOWNACTION_UPACTION_CANCEL上发布新闻。当您按住按钮,然后稍后释放时,此功能正常。但是通过快速点击,释放动画在按下完成之前触发,通常结果根本就没有动画。

我希望我可以使用AnimatorSet的顺序功能将发布动画粘贴到可能已经运行的新闻动画的结尾,但没有运气。我确信我可以通过回调进行操作,但这看起来很混乱。

这里最好的方法是什么?谢谢!

2 个答案:

答案 0 :(得分:5)

我构建了一个示例Button类,用于缓冲动画并根据您的需要在队列中执行它们:

public class AnimationButton extends Button 
{
    private List<Animation> mAnimationBuffer = new ArrayList<Animation>();;
    private boolean mIsAnimating;

    public AnimationButton(Context context) 
    {
        super(context);

    }

    public AnimationButton(Context context, AttributeSet attrs) 
    {
        super(context, attrs);

    }

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

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) 
    {
        if (event.getAction() == MotionEvent.ACTION_DOWN)
        {
            generateAnimation(1, 0.75f);
            triggerNextAnimation();
        }
        else if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP)
        {
            generateAnimation(0.75f, 1);
            triggerNextAnimation();
        }

        return super.onTouchEvent(event);
    }

    private void generateAnimation(float from, float to)
    {
        ScaleAnimation scaleAnimation = new ScaleAnimation(from, to, from, to);
        scaleAnimation.setFillAfter(true);
        scaleAnimation.setDuration(500);
        scaleAnimation.setAnimationListener(new ScaleAnimation.AnimationListener() 
        {       
            @Override
            public void onAnimationStart(Animation animation) { }

            @Override
            public void onAnimationRepeat(Animation animation) { }

            @Override
            public void onAnimationEnd(Animation animation) 
            {               
                mIsAnimating = false;
                triggerNextAnimation();
            }
        });

        mAnimationBuffer.add(scaleAnimation);
    }

    private void triggerNextAnimation()
    {
        if (mAnimationBuffer.size() > 0 && !mIsAnimating)
        {
            mIsAnimating = true;
            Animation currAnimation = mAnimationBuffer.get(0);
            mAnimationBuffer.remove(0);

            startAnimation(currAnimation);
        }
    }

}

希望这会有所帮助:)

答案 1 :(得分:0)

看起来L Preview增加了为xml文件中的状态更改指定动画的功能。

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

相关问题