2013-04-04 14 views
10

我想建立一個TextViews的動畫,在完成之後重複它自己。如何使用ViewPropertyAnimator生成循環動畫?

,每個View我想動畫,我用的是下面這段代碼

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將無法編譯,因爲它考慮對象偵聽器未初始化。而且,我不認爲這個「遞歸」動畫調用是一個很好的解決方案,這是我首先想到的。我懷疑有一個簡單而又可靠的方法來實現循環屬性動畫,但我找不到它,所以我轉向這裏尋求幫助。

在此先感謝

+0

你可以用'CycleInterpolator'。 看我的答案[這裏](http://stackoverflow.com/a/40385244/2093236)。 – Dmide 2016-11-02 16:42:58

+0

我認爲「this」會代替監聽者使用,但是如果發生了這種情況,它可能會保留內存並泄漏。無論如何,我意識到這是近4歲了。 – 2017-03-28 19:36:30

回答

7

那麼,我要再次回答我自己。

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); 
      } 
2

不優雅的方式,但它的工作原理:

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();