Android動畫分爲三種: View動畫、幀動畫、屬性動畫
View動畫
View動畫的作用對象是View,支持四種動畫效果:平移 、縮放、旋轉、透明。四種變換效果對應着Animation四個子類: TranslateAnimation 、 ScaleAnimation 、 RotateAnimation 和 AlphaAnimation 。這四種動畫皆可以通過XML定義,也可以通過代碼來動態創建。
set標籤表示動畫集合,對應AnimationSet類,可以包含一個或若干個動畫,內部還可以嵌套其他動畫集合。
android:interpolator 表示動畫集合所採用的插值器,插值器影響動畫速度,比如非勻速動畫就需要通過插值器來控制動畫的播放過程。
android:shareInterpolator 表示集合中的動畫是否和集合共享同一個插值器,如果集合不指定插值器,那麼子動畫就需要單獨指定所需的插值器或默認值。
translate、 scale 、 rotate、 alpha 這幾個子標籤分別代表四種變換效果。
Animation通過setAnimationListener方法可以給View動畫添加過程監聽。
自定義View動畫需要繼承 Animation 這個抽象類,重寫它的 initialize 和 applyTransformation 方法。 在 initialize 方法中做一些初始化工作,在 applyTransformation 中進行相應的矩陣變換即可,很多時候需要採用 Camera 來簡化矩陣變換的過程。自定義View動畫的過程主要是矩陣變 換的過程。
幀動畫是順序播放一組預先定義好的圖片,使用簡單,但容易引起OOM,所以在使用幀動畫 時應儘量避免使用過多尺寸較大的圖片。
View動畫的特殊使用場景
LayoutAnimation作用於ViewGroup,爲ViewGroup指定一個動畫,當他的子元素出場的時候都會具有這種動畫,ListView上用的多,LayoutAnimation也是一個View動畫。
anim_layout:
<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:animationOrder="normal"
android:delay="0.3" android:animation="@anim/anim_item"/>
anim_item:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:shareInterpolator="true">
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0" />
<translate
android:fromXDelta="300"
android:toXDelta="0" />
</set>
使用LayoutAnimation:
第一種方法、爲需要的ViewGroup指定android:layoutAnimation屬性
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layoutAnimation="@anim/anim_layout"/>
第二種方法、通過LayoutAnimationController來實現
Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_item);
LayoutAnimationController controller = new LayoutAnimationController(animation);
controller.setDelay(0.5f);
controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
listview.setLayoutAnimation(controller);
在startActivity(Intent)或finish()之後調用overridePendingTransition(int enterAnim,int exitAnim)方法。
Fragment也可以添加切換動畫,通過FragmentTransaction中的setCustomAnimations()方法來添加;需考慮兼容性使用View動畫,屬性動畫是API11新引入的。
屬性動畫
API 11後加入,可以在一個時間間隔內完成對象從一個屬性值到另一個屬性值的改變。因此與 View動畫相比,屬性動畫幾乎無所不能,只要對象有這個屬性,它都能實現動畫效果。API11 以下可以通過 nineoldandroids 庫來兼容以前版本。
屬性動畫有以下三種使用方法:
- ObjectAnimator:
ObjectAnimator.ofFloat(view,"translationY",values).start();
- ValueAnimator:
ValueAnimator colorAnim = ObjectAnimator.ofInt(view,"backgroundColor",/*red*/0xff
ff8080,/*blue*/0xff8080ff);
colorAnim.setDuration(2000);
colorAnim.setEvaluator(new ArgbEvaluator());
colorAnim.setRepeatCount(ValueAnimator.INFINITE);
colorAnim.setRepeatMode(ValueAnimator.REVERSE);
colorAnim.start();
- AnimatorSet
AnimatorSet set = new AnimatorSet();
set.playTogether(animator1,animator2,animator3);
set.setDuration(3*1000).start();
也可以通過在xml中定義在 res/animator/ 目錄下:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
....../>
<animator
....../>
</set>
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(context , R.animator.ani
m);
set.setTarget(view);
set.start();
set 標籤對應 AnimatorSet , animator對應 ValueAnimator ,而objectAnimator則對 應 ObjectAnimator 。
理解插值器和估值器
時間插值器(TimeInterpolator)的作用是根據時間流逝的百分比來計算出當前屬性值改變的百分比,系統預置的有LinearInterpolator(線性插值器:勻速動畫),AccelerateDecelerateInterpolator(加速減速插值器:動畫兩頭慢中間快),DecelerateInterpolator(減速插值器:動畫越來越慢)。
估值器(TypeEvaluator)的作用是根據當前屬性改變的百分比來計算改變後的屬性值。系統預置有IntEvaluator 、FloatEvaluator 、ArgbEvaluator。
整形估值器源碼:
public class IntEvaluator implements TypeEvaluator<Integer> {
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
int startInt = startValue;
return (int)(startInt + fraction * (endValue - startInt));
}
}
插值器和估值器除了系統提供之外,我們還可以自定義。自定義插值器需要實現Interpolator或者TimeInterpolator;自定義估值器算法需要實現TypeEvaluator。
屬性動畫的監聽器
public static interface AnimatorListener {
void onAnimationStart(Animator animation); //動畫開始
void onAnimationEnd(Animator animation); //動畫結束
void onAnimationCancel(Animator animation); //動畫取消
void onAnimationRepeat(Animator animation); //動畫重複播放
}
爲了方便開發,系統提供了AnimatorListenerAdapter類,它是AnimatorListener的適配器類, 可以有選擇的實現以上4個方法。
AnimatorUpdateListener會監聽整個動畫的過程,動畫由許多幀組成的,每播放一幀,onAnimationUpdate就會調用一次。
/**
* Implementors of this interface can add themselves as update listeners
* to an <code>ValueAnimator</code> instance to receive callbacks on every animati
on
* frame, after the current frame's values have been calculated for that
* <code>ValueAnimator</code>.
*/
public static interface AnimatorUpdateListener {
/**
* <p>Notifies the occurrence of another frame of the animation.</p>
*
* @param animation The animation which was repeated.
*/
void onAnimationUpdate(ValueAnimator animation);
}
對任意屬性做動畫
屬性動畫要求作用的對象提供該屬性的get和set方法,屬性動畫根據外界傳遞的該屬性的初始值和最終值,通過多次調用set方法來實現動畫效果。
如果你的對象沒有對應的get和set方法
- 請給你的對象加上get和set方法,如果你有權限的話(如果直接使用系統的類,是無法加上的);
- 用一個類來包裝原始對象,間接爲其提供get和set方法;
public class ViewWrapper {
private View target;
public ViewWrapper(View target) {
this.target = target;
}
public int getWidth() {
return target.getLayoutParams().width;
}
public void setWidth(int width) {
target.getLayoutParams().width = width;
target.requestLayout();
}
}
- 採用ValueAnimator,監聽動畫過程,自己實現屬性的改變;
/** 使用ValueAnimator 監聽動畫過程 自己實現屬性改變
*
* @param target 作用的View
* @param start 動畫起始值
* @param end 動畫終止值
*/
private void startValueAnimator(final View target, final int start, final int end) {
ValueAnimator valueAnimator = ValueAnimator.ofInt(1, 100);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
private IntEvaluator mEvaluation = new IntEvaluator();//新建一個整形估值起 方便估值使用
@Override
public void onAnimationUpdate(ValueAnimator animation) {
//獲得當前動畫的進度值 1~100之間
int currentValue = (int) animation.getAnimatedValue();
Log.e("Anim", "currentValue: " + currentValue);
//獲得當前進度佔整個動畫過程的比例,浮點型,0~1之間
float fraction = animation.getAnimatedFraction();
//調用估值器,通過比例計算出寬度 ,再設置給Button
int targetWidth = mEvaluation.evaluate(fraction, start, end);
target.getLayoutParams().width = targetWidth;
target.requestLayout();
}
});
}
屬性動畫的工作原理
通過反射調用get/set方法;屬性動畫需要運行在有Looper的線程中。
使用動畫的注意事項
-
使用幀動畫時,當圖片數量較多且圖片分辨率較大的時候容易出現OOM,需注意,儘量避免使用幀動畫。
-
使用無限循環的屬性動畫時,在Activity退出時及時停止,否則將導致Activity無法釋放從而造成內存泄露。
-
View動畫是對View的影像做動畫,並不是真正的改變了View的狀態,因此有時候會出現動畫完成後View無法隱藏(setVisibility(View.GONE)失效),這時候調用view.clearAnimation()清理View動畫即可解決。
-
不要使用px,使用px會導致不同設備上有不同的效果。
-
View動畫是對View的影像做動畫,View的真實位置沒有變動,也就導致點擊View動畫後的位置觸摸事件不會響應,屬性動畫不存在這個問題。
-
使用動畫的過程中,使用硬件加速可以提高動畫的流暢度。
-
動畫在3.0以下的系統存在兼容性問題,特殊場景可能無法正常工作,需做好適配工作。