如何在安卓系统中停止动画

7

需求:

我需要按顺序运行多个动画。我正在使用onAnimationEnd()来实现。

在动画过程中,如果触发了触摸事件,我需要停止动画并在该位置显示一个新的图像。

问题:

  1. 在onTouch事件中使用clearAnimation()会导致整个动画被删除。我的意图是停止动画并在触摸部分显示一个新的图像。如何实现这一点?

  2. 由于clearAnimation(),onAnimationEnd()被调用多次,我在按顺序运行动画时遇到问题。

  3. 是否有仅停止动画而不完全删除它的函数?我正在使用Android 2.1。

@Override
public boolean onTouch(View v, MotionEvent event) {      
    switch(event.getAction()) {
        case MotionEvent.ACTION_UP:
            imageArray[g_animCount - 1].clearAnimation();          
            break;

        default:
            break;
    }

    return true; // indicate event was handled
}

@Override
public void onAnimationEnd(Animation animation) {
    layout.removeView(imageArray[g_animCount - 1]);
    if ( (g_animCount < count))
    {               
        startNextAnimation();
    }
    else
    {
        g_animCount = 0;
        isBegin = false;
    }
}

public void startNextAnimation()
{
     int j = random.nextInt(200);
     layoutParams.setMargins(j, -20, 30, 0);
     layout.addView(imageArray[g_animCount], layoutParams); 
     imageArray[g_animCount].startAnimation(movArray[g_animCount]);
     g_animCount++;
}
1个回答

9

动画只会移动屏幕上的像素,而不是物体的位置。要让您的物体在结束时保持在原位,请设置您的

animation.setFillAfter(true);

要实际移动物体的位置,请查看使用下面代码片段的修改版本。
MarginLayoutParams marginParams = new MarginLayoutParams(object.getLayoutParams());
marginParams.setMargins(left, (top+hol2), left, 0);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
object.setLayoutParams(layoutParams);

关于onAnimationEnd被多次调用的问题,我需要看一些代码。
我所知道的手动停止动画的唯二方法是:
animation.cancel(); (may not work for 2.1, can't remember)

或者

object.clearAnimation();

以下是示例代码:
    upmotionleft = new TranslateAnimation(0, 0, 0, 600);
    upmotionleft.setDuration(2000);
    upmotionleft.setFillEnabled(true);
    upmotionleft.setAnimationListener(new Animation.AnimationListener() 
    {
        @Override
        public void onAnimationStart(Animation animation) 
        {}
        @Override
        public void onAnimationEnd(Animation animation) 
        {
            //sets to wherever I want the final object to be
            MarginLayoutParams marginParams = new MarginLayoutParams(object.getLayoutParams());
            marginParams.setMargins(left, top-hol2, left, 0);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
            object.setLayoutParams(layoutParams);

            //starts next animation
            object.startAnimation(nextAnimation);
        }

        @Override
        public void onAnimationRepeat(Animation animation) 
        {}
    });

object.startAnimation(upmotionleft);

这段代码是从我的一个项目中复制粘贴而来,但已经做了一些修改,应该仍然可以运行。

@testingtester 清除动画是否必须确保调用onAnimationEnd()? - hellodear

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接