1.幀動畫:將圖片一張張的播放,從而達到一種動畫效果。它容易產生OOM,使用中應該避免使用過多的尺寸較大的圖片。
實現步驟:
1.在res/drawable/目錄下定義一個XML動畫文件;
2.在Java代碼中調用start()方法開啓動畫。
京東動畫實現
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/a_0"
android:duration="100" />
<item
android:drawable="@drawable/a_1"
android:duration="100" />
<item
android:drawable="@drawable/a_2"
android:duration="100" />
</animation-list>
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frame_animation);
ImageView animationImg1 = (ImageView) findViewById(R.id.animation1);
animationImg1.setImageResource(R.drawable.frame_anim1);
AnimationDrawable animationDrawable1 = (AnimationDrawable) animationImg1.getBackground;
animationDrawable1.start();
}
2.補間動畫/View動畫:可以對View實現透明度(對應AlphaAnimation類)、旋轉(RotateAnimation)、
平移(TranslateAnimation)、縮放(ScaleAnimation)四種動畫操作。
這四種動畫既可以通過XML文件來定義,也可以通過代碼動態創建。爲了動畫可讀性更好,推薦使用XML文件來定義動畫。
使用步驟:
1.在res/anim/文件夾下定義一個動畫資源文件;
2.在JAVA代碼中按照如下方式加載這個動畫。
eg:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="true">
<alpha
android:duration="300"
android:fromAlpha="0"
android:toAlpha="1" />
<rotate
android:duration="600"
android:fromDegrees="0"
android:toDegrees="90" />
<scale
android:duration="400"
android:fromXScale="0.5"
android:fromYScale="0.5"
android:toXScale="2"
android:toYScale="2" />
<translate
android:duration="100"
android:fromXDelta="0"
android:fromYDelta="0"
android:toXDelta="100"
android:toYDelta="100" />
</set>
// 使用AnimationUtils工具類加載res/anim/下面的一個動畫資源文件
Animation animation= AnimationUtils.loadAnimation(MainActivity.this,R.anim.alpha_animation);
/*
* 也可以使用JAVA代碼創建動畫
* AlphaAnimation animation = new AlphaAnimation(0, 1);
animation.setDuration(3000);
*
* */
// 對按鈕進行動畫操作
btn.startAnimation(animation);
3.屬性動畫:API11新加入的特性,操作對象不限於View,而是對任意對象。它對應着三個類:ObjectAnimator(繼承自ValueAnimator
)、ValueAnimator、AnimatorSet(動畫集)。
可以在res/animator/下面定義一個屬性動畫的XML文件,但是有些對象的屬性起始值無法預先知道,因此推薦在代碼中動態創建。
eg:
// 使用屬性動畫改變按鈕的背景色,在3秒內實現顏色從藍色漸變爲綠色,動畫會無限播放並且會有反轉效果 ObjectAnimator colorAnim=ObjectAnimator.ofInt(btn,"backgroundColor", Color.BLUE,Color.GREEN); colorAnim.setDuration(3000); colorAnim.setEvaluator(new ArgbEvaluator()); colorAnim.setRepeatCount(ValueAnimator.INFINITE); colorAnim.setRepeatMode(ValueAnimator.REVERSE); colorAnim.start();