左右晃動的效果: (這邊顯示沒那麼流暢)
一、續播 (不知道取什麼名字好,就是先播放動畫A, 接著播放動畫B)
有兩種方式。
第一種,分別動畫兩個動畫,A和B, 然後先播放動畫A,設定A 的 AnimationListener。當onAnimationEnd觸發(即A播放完畢)時,開始播放B。
animation1.setAnimationListener(new Animation.AnimationListener() {@Overridepublic void onAnimationStart(Animation animation) {}@Overridepublic void onAnimationRepeat(Animation animation) {}@Overridepublic void onAnimationEnd(Animation animation) {animation2.start();}});
第二種,寫一個動畫集AnimationSet,在其中定義動畫A和B,為動畫B設定startOffset, 其值就是前一個動畫播放的所需的時間。
這邊舉一個例子,動畫A是 透明度從 0.1 到 1.0 , 動畫B是透明度從1.0到0.1, 使用下面這個動畫集你就可以看到整個變化過程。
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"><alpha android:fromAlpha="0.2" android:toAlpha="1.0" android:duration="3000" /> <alpha android:startOffset="3000" android:fromAlpha="1.0" android:toAlpha="0.2" android:duration="3000" /></set>
其中android:startOffset="3000" 表示延遲3秒後再執行。 如果去掉其中的 android:startOffset="3000" , 你就什麼效果也看不到了。 因為兩個動畫會同時播放。
二、迴圈
有時候,我們可能需要實現一個圖片不停閃爍的功能(比如天氣預報中的緊急警報功能), 或者有的時候我們需要實現圖片左右晃動,都需要迴圈動畫來實現。
同樣,也有兩種辦法。
第一種,設定兩個動畫A 和 B, 動畫A 是透明度 0 -1, 動畫B是1 - 0, 然後對這兩個動畫都進行監聽, A 結束執行B, B結束執行A.. 無限迴圈...
第二種,利用Animation的setRepeatCount、setRepeatMode來實現動畫迴圈。
比如閃爍(透明度亮 -> 暗, 暗->亮,如此迴圈)
//閃爍 AlphaAnimation alphaAnimation1 = new AlphaAnimation(0.1f, 1.0f); alphaAnimation1.setDuration(3000); alphaAnimation1.setRepeatCount(Animation.INFINITE); alphaAnimation1.setRepeatMode(Animation.REVERSE); iv.setAnimation(alphaAnimation1); alphaAnimation1.start();
alphaAnimation1.setRepeatCount(Animation.INFINITE); 表示重複多次。 也可以設定具體重複的次數,比如alphaAnimation1.setRepeatCount(5);
alphaAnimation1.setRepeatMode(Animation.REVERSE);表示動畫結束後,反過來再執行。 該方法有兩種值, RESTART 和 REVERSE。 RESTART表示從頭開始,REVERSE表示從末尾倒播。
懶得螢幕錄影了,類似下面的效果:
再比如左右搖擺
//搖擺 TranslateAnimation alphaAnimation2 = new TranslateAnimation(150f, 350f, 50, 50); alphaAnimation2.setDuration(1000); alphaAnimation2.setRepeatCount(Animation.INFINITE); alphaAnimation2.setRepeatMode(Animation.REVERSE); iv.setAnimation(alphaAnimation2); alphaAnimation2.start();
其中 iv 是一個ImageView。
好了,就寫這麼多。