首页 > 解决方案 > TranslateAnimation 无法正常工作

问题描述

部分代码可以正常工作。然而,在第二种情况下,动画发生了,但不是以适当的方式发生的。

应该滑动的视图会跳转到它们各自的位置(它们会转到正确的位置,但动画不正确)。

有没有人可以解决这种不良行为?

GIF 显示问题在此处输入图像描述

代码:

 public void animateCollapse(){

        final int count = getChildCount();
        final int tWidth = getMeasuredWidth();
        int widthSum = 0;
        for (int i = 0; i < count; i++) {
            final RelativeLayout child = (RelativeLayout) getChildAt(i);
            widthSum += child.getWidth();
            child.clearAnimation();
        }
       if(!mTagLayout.isCollapsed()){

         //Removed piece of code, that works. 
        }
       } else{
           int currentPosX = 0;
           if(tWidth> widthSum) return;

           for (int i = 0; i < count; i++) {
               final View child = getChildAt(i);

               int lastpos = tWidth - child.getMeasuredWidth();

               float value =currentPosX - child.getX();
                       TranslateAnimation anim = new TranslateAnimation(0, value, 0, 0);
               anim.setDuration(1000);

               anim.setAnimationListener(new TranslateAnimation.AnimationListener() {

                   @Override
                   public void onAnimationStart(Animation animation) { }

                   @Override
                   public void onAnimationRepeat(Animation animation) { }

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

               anim.setFillAfter(true);
               child.startAnimation(anim);
               currentPosX += child.getMeasuredWidth();

               mTagLayout.setCollapsed(false);

           }
       }

@Edit 在动画期间视图不会被破坏和重建

标签: android

解决方案


我通过使用反向插值器修复

 if (mTagLayout.isCollapsed()) {
      anim.setInterpolator(new ReverseInterpolator());
      mTagLayout.setCollapsed(false);
 } else {
      mTagLayout.setCollapsed(true);
 }


public class ReverseInterpolator implements Interpolator {
    @Override
    public float getInterpolation(float paramFloat) {
        return Math.abs(paramFloat - 1f);
    }
}

推荐阅读