一、簡介
Frame Animation(AnimationDrawable對象):幀動畫,就像GIF圖片,通過一系列Drawable依次顯示來模擬動畫的效果。
必須以<animation-list>爲根元素,以<item>表示要輪換顯示的圖片,duration屬性表示各項顯示的時間。XML文件要放在/res/anim/或者/res/animator目錄下。
二、代碼實現
在frame_animation.xml下
<?xml version="1.0" encoding="utf-8" ?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@mipmap/lw0" android:duration="50" />
<item android:drawable="@mipmap/lw1" android:duration="50" />
<item android:drawable="@mipmap/lw2" android:duration="50" />
<item android:drawable="@mipmap/lw3" android:duration="50" />
<item android:drawable="@mipmap/lw4" android:duration="50" />
<item android:drawable="@mipmap/lw5" android:duration="50" />
<item android:drawable="@mipmap/lw6" android:duration="50" />
<item android:drawable="@mipmap/lw7" android:duration="50" />
<item android:drawable="@mipmap/lw8" android:duration="50" />
<item android:drawable="@mipmap/lw9" android:duration="50" />
</animation-list>
drawable是綁定圖片,duration是設置每張圖片持續時間
主頁面的xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lw.frameanimation_demo.MainActivity">
<ImageView
android:id="@+id/myImageView"
android:layout_centerInParent="true"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="@anim/frame_animation"/>
<Button
android:layout_centerHorizontal="true"
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open/Stop"/>
</RelativeLayout>
MainActivity代碼
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button button;
private AnimationDrawable animationDrawable = null;
private void initView(){
imageView = (ImageView) findViewById(R.id.myImageView);
button = (Button) findViewById(R.id.myButton);
//mageView.setBackgroundResource(R.anim.frame_animation);
animationDrawable = (AnimationDrawable) imageView.getDrawable();
}
private void initCtrl(){
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//每次從頭開始播放
if(!animationDrawable.isRunning()){
//是否執行一次
animationDrawable.setOneShot(false);
animationDrawable.start();
}else{
animationDrawable.setOneShot(false);
animationDrawable.stop();
}
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initCtrl();
}
//進入的時候播放
// SDK中提到,不要在onCreate()中調用start(),因爲AnimationDrawable還沒有完全跟Window相關聯,如果想要界面顯示時就開始動畫的話,可以在onWindowFoucsChanged()中調用start()。
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
animationDrawable.setOneShot(false);
animationDrawable.start();
}
}
}
其中: