如何在Android中停止动画

pav*_*van 6 animation android imageview

需求:

我需要逐个运行多个动画.我正在使用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++;
}
Run Code Online (Sandbox Code Playgroud)

tes*_*ter 9

动画仅移动屏幕上的像素,而不移动对象的位置.为了让你留在它的最后,设置你的

animation.setFillAfter(true);
Run Code Online (Sandbox Code Playgroud)

要实际移动对象的位置,请查看使用以下代码段的修改版本.

MarginLayoutParams marginParams = new MarginLayoutParams(object.getLayoutParams());
marginParams.setMargins(left, (top+hol2), left, 0);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
object.setLayoutParams(layoutParams);
Run Code Online (Sandbox Code Playgroud)

关于多次调用onAnimationEnd,我需要看一些代码.

我知道手动停止动画的唯一两种方法是

animation.cancel(); (may not work for 2.1, can't remember)
Run Code Online (Sandbox Code Playgroud)

要么

object.clearAnimation();
Run Code Online (Sandbox Code Playgroud)

示例代码如下:

    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);
Run Code Online (Sandbox Code Playgroud)

这段代码是从我的项目中复制和粘贴的,但它已经有所改变,应该仍然运行.