(啊,一不小心把這篇文章刪了,沒有備份,只能重來了。)
在API Demo的View->Animation下可以找到四個Animation的Demo,第一個3D Translate比較複雜,最後再講,先講第2個Interpolator。該Activity對應的是view包內的Animation3.java,和layout的animation_3.xml。
介面的布局不加解釋了,就一個Spinner和一個TextView。不是本文內容。
主要解釋下幾個重點語句。
初始化Animation,從類的名字可以看出是一個變換View的位置的動畫,參數起點橫座標,終點橫座標,起點縱座標,終點縱座標。
Animation a = new TranslateAnimation(0.0f,<br /> targetParent.getWidth() - target.getWidth() - targetParent.getPaddingLeft() -<br /> targetParent.getPaddingRight(), 0.0f, 0.0f);
下面是動畫的參數設定,我加上了注釋
a.setDuration(1000);//設定動畫所用的時間<br /> a.setStartOffset(300);//設定動畫啟動的延時<br /> //設定重複模式,RESTART為結束後重新開始,REVERSE為按原來的軌跡逆向返回<br /> a.setRepeatMode(Animation.RESTART);<br /> //設定重複次數,INFINITE為無限<br /> a.setRepeatCount(Animation.INFINITE);<br /> //根據使用者在Spinner的選擇設定target的進入的方式<br /> switch (position) {<br /> case 0:<br /> //加速進入<br /> a.setInterpolator(AnimationUtils.loadInterpolator(this,<br /> android.R.anim.accelerate_interpolator));<br /> break;<br /> case 1:<br /> //減速進入<br /> a.setInterpolator(AnimationUtils.loadInterpolator(this,<br /> android.R.anim.decelerate_interpolator));<br /> break;<br /> case 2:<br /> //加速進入.與第一個的區別為當repeatMode為reverse時,仍為加速返回原點<br /> a.setInterpolator(AnimationUtils.loadInterpolator(this,<br /> android.R.anim.accelerate_decelerate_interpolator));<br /> break;<br /> case 3:<br /> //先往後退一點再加速前進<br /> a.setInterpolator(AnimationUtils.loadInterpolator(this,<br /> android.R.anim.anticipate_interpolator));<br /> break;<br /> case 4:<br /> //減速前進,衝過終點前再後退<br /> a.setInterpolator(AnimationUtils.loadInterpolator(this,<br /> android.R.anim.overshoot_interpolator));<br /> break;<br /> case 5:<br /> //case 3,4的結合體<br /> a.setInterpolator(AnimationUtils.loadInterpolator(this,<br /> android.R.anim.anticipate_overshoot_interpolator));<br /> break;<br /> case 6:<br /> //停止前來回振幾下<br /> a.setInterpolator(AnimationUtils.loadInterpolator(this,<br /> android.R.anim.bounce_interpolator));<br /> break;<br /> }<br /> //讓target開始執行這個動畫<br /> target.startAnimation(a);<br /> }
這裡使用的是Android已預設的一些動作,我們也可以自訂XML來實現更好看的動畫效果的,這個下一篇再講。
除了TranslationAnimation,還有AlphaAnimation、RotateAnimation、ScaleAnimation,使用這幾個基體動作的組合,可以形成一系列複雜的動畫效果。具體用法請查看SDK。
整個都比較簡單,就一個函數的調用,還不懂的看一下API的注釋和SDK文檔,沒什麼難理解的。