利用XML建立動畫資源檔,之後再將它呼叫進來使用比較簡單
res/anum/frame.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list
xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true">
<item
android:drawable="@drawable/anim1"
android:duration="50"/>
<item
android:drawable="@drawable/anim2"
android:duration="50"/>
<item
android:drawable="@drawable/anim3"
android:duration="50"/>
<item
android:drawable="@drawable/ic_action_search"
android:duration="50"/>
</animation-list>
主程式
package com.example.frameanim;
import ...
public class MainActivity extends Activity {
//宣告AnimationDrawable物件變數
AnimationDrawable ad;
//宣告ImageView,動畫會顯示在上面
ImageView iv;
Button but1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but1 = (Button) findViewById(R.id.button1);
iv = (ImageView) findViewById(R.id.imageView1);
//取得資源物件,再取得動畫資源檔,取回來之後必須轉型回與變數相同的型別
ad=(AnimationDrawable) this.getResources().getDrawable(R.anim.frame);
//將AnimationDrawable物件設定給ImageView準備播放
iv.setImageDrawable(ad);
}
@Override
//觸碰螢幕的事件處理
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//true為止播一次,false為循環播放
ad.setOneShot(false);
ad.start();
}
return true;
}
public void but1_onclick(View v) {
if (!ad.isRunning()) {
ad.setOneShot(false);
ad.start();
but1.setText("stop");
} else {
ad.stop();
but1.setText("start");
}
}
}
Nice
回覆刪除