Animations是Android的UI實現動態效果的API。
主要包含兩類,一類是Tweened Animations, 一類是是frame-by-frame Animations。
第一類是對一個view的處理,而第二類是對一個drawable序列的處理。
這兩類效果既可以在代碼中實現,也可以在xml中實現。
這裏介紹下在xml中的實現。
Tweened Animations提供了rotate(旋轉)、alpha(淡入淡出)、translate(移動)、Scale(縮放)四種效果。
在new xml中RT選擇Tween Animation,選擇set新建。
rotate:
< set xmlns:android= "http://schemas.android.com/apk/res/android" >
<!-- 動畫時間 -->
<!-- 開始角度 -->
<!-- 結束角度 -->
<!-- 逆時針旋轉270度 -->
<rotate
android:duration= "2000"
android:fromDegrees= "0"
android:toDegrees= "270" />
</ set>
alpha:
< set xmlns:android= "http://schemas.android.com/apk/res/android" >
<!-- 動畫時間 -->
<!-- 開始透明度 -->
<!-- 結束透明度 -->
<alpha
android:duration= "2000"
android:fromAlpha= "1"
android:toAlpha= "0.1" />
</ set>
scale:
< set xmlns:android= "http://schemas.android.com/apk/res/android" >
<!-- 動畫時間 -->
<!-- x,y軸起始壓縮 -->
<!-- x,y軸結束壓縮 -->
<scale
android:duration= "2000"
android:fromXScale= "0"
android:fromYScale= "1"
android:toXScale= "1"
android:toYScale= "1" />
</ set>
translate:
< set xmlns:android= "http://schemas.android.com/apk/res/android" >
<!-- x,y軸起始座標 -->
<!-- x,y軸結束座標 -->
<!-- 動畫時間 -->
<translate
android:fromXDelta= "0%"
android:toXDelta= "100%"
android:fromYDelta= "0%"
android:toYDelta= "100%"
android:duration= "2000" />
</ set>
在代碼中引用:
View view = findViewById(R.id. img);
Animation animation = AnimationUtils.loadAnimation(MainActivity. this, R.anim. alpha);
view.setAnimation(animation);
frame-by-frame Animations,可以用於顯示gif圖,直接使用第三方庫+gif圖,難免會報OOM。
在new xml中RT選擇Drawable,選擇animation-list新建mylist。
< animation-list xmlns:android ="http://schemas.android.com/apk/res/android" >
<item android:duration = "40" android:drawable ="@drawable/icon_000" />
<item android:duration = "40" android:drawable ="@drawable/icon_001" />
<item android:duration = "40" android:drawable ="@drawable/icon_002" />
<item android:duration = "40" android:drawable ="@drawable/icon_003" />
<item android:duration = "40" android:drawable ="@drawable/icon_004" />
<!-- 只要有幀圖,就還可以繼續往下寫 -->
</ animation-list>
引用:
ImageView img = (ImageView) findViewById(R.id.img);
img.setBackgroundResource(R.anim. mylist);
AnimationDrawable animationDrawable = (AnimationDrawable) img.getBackground();
animationDrawable.start();