2012-01-31 86 views
7

我有一個TextView,我想倒數(3 ... 2 ... 1 ...發生的東西)。Android簡單的TextView動畫

爲了讓它更有趣一點,我希望每個數字都以完全不透明的方式開始,然後淡入透明。

有沒有簡單的方法來做到這一點?

回答

11

嘗試是這樣的:

private void countDown(final TextView tv, final count) { 
    if (count == 0) { 
    tv.setText(""); //Note: the TextView will be visible again here. 
    return; 
    } 
    tv.setText(count); 
    AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f); 
    animation.setDuration(1000); 
    animation.setAnimationListener(new AnimationListener() { 
    public void onAnimationEnd(Animation anim) { 
     countDown(tv, count - 1); 
    } 
    ... //implement the other two methods 
    }); 
    tv.startAnimation(animation); 
} 

我只是打字出來,所以它可能無法編譯原樣。

+1

用'tv.setText(String.valueOf(count))'替換'tv.setText(count);''和代碼工作正常 – 2015-03-24 23:00:00

2

看看CountDownAnimation

我首先嚐試了@dmon解決方案,但是由於每個動畫都是在前一個動畫的結尾處開始的,因此在多次調用之後最終會出現延遲。

因此,我實現了CountDownAnimation類,它使用了HandlerpostDelayed函數。默認情況下,它使用alpha動畫,但可以設置任何動畫。您可以下載項目here

4

我用更傳統的Android風格的動畫,這一點:

 ValueAnimator animator = new ValueAnimator(); 
     animator.setObjectValues(0, count); 
     animator.addUpdateListener(new AnimatorUpdateListener() { 
      public void onAnimationUpdate(ValueAnimator animation) { 
       view.setText(String.valueOf(animation.getAnimatedValue())); 
      } 
     }); 
     animator.setEvaluator(new TypeEvaluator<Integer>() { 
      public Integer evaluate(float fraction, Integer startValue, Integer endValue) { 
       return Math.round((endValue - startValue) * fraction); 
      } 
     }); 
     animator.setDuration(1000); 
     animator.start(); 

您可以用0count值起到使計數器任意數量的去到任何數量,以及與玩1000設置整個動畫的持續時間。

請注意,這支持Android API級別11及以上,但您可以使用真棒nineoldandroids項目使其輕鬆向後兼容。