通過AnimationDrawable實現android中的幀動畫

在android中實現簡單的幀動畫,如在清理緩存的時候會出現的一掃一掃的動畫,在這裏我們實現一下,

首先,在xml中寫出要顯示的圖片,和每張圖片的播放間隔,其中是200毫秒,也就是0.2秒

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:drawable="@drawable/broom_left"
        android:duration="200">
    </item>
    <item
        android:drawable="@drawable/broom_center"
        android:duration="200">
    </item>
    <item
        android:drawable="@drawable/broom_right"
        android:duration="200">
    </item>

</animation-list>

然後再佈局文件裏放一個view或者ImageView設置背景爲上一個xml

<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"
   	android:background="#775566" >

    <ImageView
        android:id="@+id/im_animation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/broom_animation" />

</RelativeLayout>
之後再主函數裏聲明AnimationDrawable和imageview,接着在start一下AnimationDrawable至於AnimationDrawable的一些操作可以在網上查找一些

package com.example.deletcache;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {
	private AnimationDrawable animation;
	private ImageView img;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		// TODO Auto-generated method stub
		// animation = (AnimationDrawable) findViewById(R.id.im_animation);
		img = (ImageView) findViewById(R.id.im_animation);
		animation = (AnimationDrawable) img.getBackground();
		animation.start();
	}
}
其中的
animation = (AnimationDrawable) img.getBackground();
不要忘了


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章