之前對Android動畫這塊一直是一知半解,知道個大概,並不會使用。剛好這幾天沒有太多的任務要做,可以梳理一下Android動畫的一些知識。Android Animation的基礎用法就不說了,這里主要記錄下簡單實用中遇到的問題。
1.XML中AnimationSet的某些屬性有些問題。
主要就是android:repeatCount,android:repeatMode無效。這個問題據說是Google的工程師刻意為之。【參考:http://stackoverflow.com/questions/4480652/android-animation-does-not-repeat】。
不過也有一些補救措施,比如可以給Animation設置AnimationListener。然后在onAnimationEnd()方法中,重新開始一遍動畫即可。
2.AnimationSet的動畫添加順序問題。
由於AnimationSet的addAnimation()方法添加的動畫會按照添加動畫的順序進行矩陣變化等等處理,所以假設有一系列的動畫(不只有一個變換位置的動畫)作用於A上使得A轉換成了B,那么如果想通過另外一系列動畫使得B還轉換成之前的A,最好保證前后兩次轉換的動畫的順序相同。比如圖片image先后經過動畫:a,b,c變換成image2,如果想再從image2變換成image,那么動畫的順序也需要a,b,c(當然這個前提是要有多個可能產生位置變化的動畫)
舉個例子:在XML中定義動畫:先ronate、然后alpha、接着scale,最后translate。
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:re > <rotate android:duration="3000" android:fromDegrees="0" android:pivotX="50%" android:pivotY="50%" android:toDegrees="360" > </rotate> <alpha android:duration="3000" android:fromAlpha="1.0" android:startOffset="0" android:toAlpha="0.5" /> <scale android:duration="3000" android:fromXScale="1.0" android:fromYScale="1.0" android:pivotX="50%" android:pivotY="50%" android:toXScale="4" android:toYScale="4" > </scale> <translate android:duration="3000" android:fromXDelta="0" android:fromYDelta="0" android:toXDelta="-100" android:toYDelta="-800" > </translate> </set>
如果需要在把動畫還原,需要:
AlphaAnimation alphaAnimation = new AlphaAnimation(0.5f, 1.0f); RotateAnimation rotateAnimation = new RotateAnimation(360f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); ScaleAnimation scaleAnimation = new ScaleAnimation(4.0f, 1.0f, 4.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); TranslateAnimation translateAnimation = new TranslateAnimation( Animation.ABSOLUTE, -100, Animation.ABSOLUTE, 0, Animation.ABSOLUTE, -800, Animation.ABSOLUTE, 0); AnimationSet set = new AnimationSet( true); set.setInterpolator(new AccelerateDecelerateInterpolator()); set.addAnimation(alphaAnimation); set.addAnimation(scaleAnimation); set.addAnimation(rotateAnimation); set.addAnimation(translateAnimation); set.setDuration(3000);
不然就有可能在轉換的過程中,動畫不流暢,出現閃動的現象。