2012-04-12 74 views
5

目標 我想實現一個從左到右滾動數字(不是圖形)的倒數計時器。如何實現水平滾動倒數計時器?

效果 效果看起來像數字從左邊變大,向中間變慢,然後向右變大。

注意 由於我已經在使用一個TimerTask來執行代碼每一秒,我可以用它來觸發下一個數字在整個水平滾動的TextView滾動。

難道這只是作爲一個textview內滾動視圖實現?尋找一個代碼示例,以開始....

回答

9

使用動畫將是最簡單的解決方案。您可以創建自己的或嘗試並結合多個TranslateAnimationsScaleAnimations

這意味着將每個數字放入其自己的TextView中,而不是使用滾動視圖。

然後你可以控制加速到中間與Interpolator。插值器是Android如何處理緩動。您可能會想要加速/減速效果的AccelerateDecelerateInterpolator

您可以使用AnimationSet將多個動畫應用於相同的視圖。弄清楚如何組合一個好的AnimationSet將是該項目最具挑戰性的部分。確保注意「填充」屬性。事實上,在玩了一段時間後,我認爲自定義動畫比使用現成的動畫更簡單。

你可以叉my GitHub project它實現了一個非常簡單的版本。 4月17日和之前我使用了多個預製動畫。如果你看最新的版本,你會看到自定義動畫。

設置一個動畫的持續時間後,每個動畫的時間將自行處理。 A Handler在前一個完成後調用下一個數字。我認爲這比每隔X秒調用一個函數來更新所有內容稍微簡單一些。

的功能概述:在

  • 一個活動(CountDownActivity.java)看到的一切。
    • Activitiy的佈局XML有一個用於開始倒計時的按鈕。
    • 倒計時開始後,按鈕消失。倒數完成後會再次出現。
  • 該活動包含HandlerMotionHandler.java)。控制數字的移動和時間。
    • 該處理器採用了AnimationSet移動數字
      • 的AnimationSet是傳遞依賴
        • 這是靈活性。簡單地傳遞在不同AnimationSet來改變電話號碼如何移動
        • 的AnimationSet由 4動畫 自定義動畫的(見下文)
    • 的AnimationSet使用共享AccelerateDecelerateInterpolator,這似乎正常工作。還有其他選擇,包括編寫自己的選項。
    • 該處理器採用了delayed message開始下一個數
    • 的處理程序通知活動時,倒計時使用自定義監聽器(MotionHandler >> CountdownListener)
  • 旋轉設備完成將重新開始倒計時。

注意 - 以前我在一個AnimationSet中使用了四個現成的動畫,我編輯過只包含一個自定義動畫......您可以根據自己的喜好調整它的算法。

此自定義動畫使用Cycloid使數字看起來越來越大。

/** 
* A custom animation to move and scale the numbers. 
* 
*/ 
public class NumberAnimation extends Animation 
{ 
    final public static float MINIMUM = 3; 
    private int mHorizontal; 
    private int mScaling; 

    public NumberAnimation(int horizontalMovement, int scaling) 
    { 
     mHorizontal = horizontalMovement; 
     mScaling = scaling; 
    } 

    @Override 
    protected void applyTransformation(float interpolatedTime, Transformation t) 
    { 
     // Cycloid repeats every 2pi - scale interpolatedTime to that 
     double time = 2 * Math.PI * interpolatedTime; 
     // Cycloid function 
     float currentScale = (float) (mScaling * (1 - Math.cos(time))) + MINIMUM; 
     Matrix matrix = t.getMatrix(); 
     matrix.preScale(currentScale, currentScale); 
     matrix.postTranslate(mHorizontal * interpolatedTime, 0); 
    } 
} 
+0

彼得,謝謝你花時間回答我的問題! – 2012-04-22 00:26:24

+0

@SomeoneSomewhere - 很有趣。希望能幫助到你! – 2012-04-22 02:58:55

相關問題