如何使用ViewPropertyAnimator生成循环动画?

10

我希望构建一个TextView的动画,该动画在完成后会自动重复播放。

对于我想要动画的每个视图,我使用以下代码:

final float oldX = v.getX();
final float newX = v.getX() - (float)totalWidth;
final AnimatorListenerAdapter listener = new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        v.setX(oldX);
        animFinished = true;

        //This line won't compile
        //v.animate().setDuration(animDuration).setInterpolator(newsInterpolator)
        //    .setListener(listener).x(newX);
    }
};

v.animate().setDuration(animDuration).setInterpolator(newsInterpolator)
    .setListener(listener).x(newX); 

我试着把最后一段代码放在onAnimationEnd里,但Java不会编译,因为它认为监听器对象未初始化。此外,我认为这种“递归”动画调用并不是一个好的解决方案,这是我脑海中想到的第一件事。我怀疑有一种简单而可靠的方法来实现循环属性动画,但我未能找到它,所以我来这里寻求帮助。提前致谢。

你可以使用 CycleInterpolator。请查看我的回答这里 - Dmide
我认为“这个”应该是代替listener使用的,但如果内存泄漏的话,它可能只会保留内存并泄漏。无论如何,我现在意识到这已经将近4年了。 - Stephen J
2个回答

8

好吧,我要再次回答自己。

TranslateAnimation类有关于重复动画的方法,因此我使用它来替代ViewPropertyAnimator。

以下代码似乎可以工作:

            long duration = 1000* ((long)totalWidth / newsScrollSpeed);
            System.out.println("totalWidth="+totalWidth);
            TranslateAnimation  anim = new TranslateAnimation(0,-totalWidth,0,0);
            anim.setInterpolator(linearInterpolator);
            anim.setDuration(duration);
            anim.setRepeatCount(TranslateAnimation.INFINITE);
            anim.setRepeatMode(TranslateAnimation.RESTART);

            for(i=0;i<this.getChildCount();i++)
            {
                View v = this.getChildAt(i);

                if(v.getId() == R.id.yuruyen_yazi)
                {
                    continue;
                }

                v.startAnimation(anim);
            }

1
不觉得这个回答解决了指定了ViewPropertyAnimator的问题。 - Trevor

3

并不是优雅的方式,但它能够工作:

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // update newX
        v.animate().setDuration(animDuration).setInterpolator(newsInterpolator).x(newX).withEndAction(this).start(); 
    }
};

v.animate().setDuration(animDuration).setInterpolator(newsInterpolator).x(newX).withEndAction(runnable).start(); 

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