Android動畫之:Frame動畫
Frame動畫是Android動畫中的一種 ,類似于我們看電影一樣,動畫是由N張圖片組成的,在地一的時間內輪流顯示圖片實現動畫現象。實現Frame動畫也有兩種方式,一種在xml中寫動畫布局,另外一種是純代碼實現 。
先看下Frame動畫的xml布局方法:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/animation_1" android:duration="500" />
<item android:drawable="@drawable/animation_2" android:duration="500" />
<item android:drawable="@drawable/animation_3" android:duration="500" />
<item android:drawable="@drawable/animation_4" android:duration="500" />
<item android:drawable="@drawable/animation_5" android:duration="500" />
<item android:drawable="@drawable/animation_6" android:duration="500" />
</animation-list>
在代碼中實現就三句代碼:
animationIv.setBackgroundResource(R.anim.test_animation); /**animationIv是我們要顯示的ImageView,已經寫在而局文件中*/
AnimationDrawable anim = (AnimationDrawable) animationIv.getBackground();
anim.start();
另外一種 就是純屬代碼實現:
public class FrameAnimationActivity extends Activity {
private Button startBtn;
private ImageView animationIv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
startBtn = (Button) findViewById(R.id.start_btn);
animationIv = (ImageView) findViewById(R.id.animation_iv);
startBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startAnimation(animationIv);
}
});
}
/**用代碼實現Frame動畫*/
private void startAnimation(ImageView iv) {
/**Frame動畫對象*/
AnimationDrawable anim = new AnimationDrawable();
/**添加動畫元素*/
for (int i = 1; i <= 6; i++) {
/**根據資源名稱和目錄獲取對應的資源ID*/
int id = getResources().getIdentifier("animation_" + i, "drawable", getPackageName());
/**根據ID獲取到Drawable對象*/
Drawable drawable = getResources().getDrawable(id);
/**添加到AnimationDrawable中,300是指動畫時間,單位:毫秒*/
anim.addFrame(drawable, 300);
}
/**設置動畫的循環方式,true為只一次,fasle為不斷循環播放*/
anim.setOneShot(false); // 設置為loop
/**設置ImageView的背景為動畫對象*/
iv.setBackgroundDrawable(anim);
/**開始動畫*/
anim.start();
}
/**放置在/res下的anim或drawable目錄中(/res/[anim | drawable]/filename.xml),文件名可以作為資源ID在代碼中引用
* 我們需要把這段代碼放在onWindowFocusChanged方法中,當Activity展示給用戶時,onWindowFocusChanged方法就會被調用,
* 我們正是在這個時候實現我們的動畫效果。onWindowFocusChanged是在onCreate之后被調用的*/
@Override
public void onWindowFocusChanged(boolean hasFocus) { //這里是用xml寫的動畫,與上面點擊事件的動畫只需保留任意一個就可以
super.onWindowFocusChanged(hasFocus);
animationIv.setBackgroundResource(R.anim.test_animation);
AnimationDrawable anim = (AnimationDrawable) animationIv.getBackground();
anim.start();
}
}