Android 中Animations的使用 代碼篇


這裏討論如何在代碼中實現Animations的效果。

注:屏幕左上角是座標零點,往下往右爲y,x正方向

在代碼中設置Animations的步驟:

1.創建一個AnimationSet對象; 

2.增加需要創建相應的Animation對象;

3.爲Animation對象設置相應的數據; 

4.將Animatin對象添加到AnimationSet對象當中; 

5.使用控件對象開始執行AnimationSet。

alpha效果:

//新建AnimationSet對象,true表示使用默認的interpolater效果
AnimationSet animationSet = new AnimationSet( true);
//設置淡入淡出效果, 1是起始透明度, 0是結束透明度
AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
//設置動畫時長
alphaAnimation.setDuration(5000);
//將動畫效果添加至集合中
animationSet.addAnimation(alphaAnimation);
//開始動畫
view.startAnimation(animationSet);

Scale效果:

//新建AnimationSet對象,true表示使用默認的 interpolater效果
AnimationSet animationSet = new AnimationSet( true);
//設置縮放效果,第一個0,1是x軸起始、結束拉伸, 第二個0,1是y軸起始、結束拉伸
ScaleAnim ation scaleAnimation = new ScaleAnimation(0, 1, 0, 1);
//設置動畫時長
scaleAnimation.setDuration(5000);
//將動畫效果添加至集合中
animationSet.addAnimation(scaleAnimation);
//開始動畫
view.startAnimation(animationSet);

Rotate效果:

//新建AnimationSet對象,true表示使用默認的 interpolater效果
AnimationSet animationSet = new AnimationSet( true);
//設置旋轉效果,從90度到270度
RotateAnimation rotateAnimation = new RotateAnimation(90, 270);
//設置動畫時長
rotateAnimation.setDuration(5000);
//將動畫效果添加至集合中
animationSet.addAnimation(rotateAnimation);
//開始動畫
view.startAnimation(animationSet);

translate效果:
// 新建AnimationSet對象,true表示使用默認的 interpolater效果
AnimationSet animationSet = new AnimationSet( true);
// 設置移動效果
//參數列表, int fromXType, float fromXValue, int toXType, float toXValue, int fromYType, float fromYValue, int toYType, float toYValue
//以fromXType,fromXValue爲例
//fromXType有三種可選的值Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF, or Animation.RELATIVE_TO_PARENT
//Animation.ABSOLUTE是絕對尺寸,當填入這個值時,Value值就可以填入具體的 dp值
//Animation.RELATIVE_TO_SELF是相對自己的尺寸,只能填入倍數,如下代碼是向右下角平移0.5個自己的長度
//Animation.RELATIVE_TO_PARENT是相對父空間的尺寸
TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF , 0f, Animation.RELATIVE_TO_SELF , 0.5f, Animation.RELATIVE_TO_SELF , 0f, Animation.RELATIVE_TO_SELF , 0.5f);
// 設置動畫時長
translateAnimation.setDuration(2000);
// 將動畫效果添加至集合中
animationSet.addAnimation(translateAnimation);
// 開始動畫
view.startAnimation(animationSet);

Animation還有一些通用方法用來設置相關狀態:

1、setFillAfter(boolean)
如果boolean爲true,則執行動畫後,控件將停留在動畫結束之後的狀態。

2、setFillBefore(boolean)
如果boolean爲true,則執行動畫後,控件將回到在動畫開始之前的狀態。

3、setStartOffSet(long)
設置動畫開始之前的等待時間。

4、setRepeatCount(int)
動畫重複執行的次數。

5、setRepeatMode(int)
當設置成Animation.INFINITE死循環執行。

ctrlz presents!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章