大家平時見到的最多的可能就是Frame動畫了,Android中當然也少不了它。它的使用更加簡單,只需要建立一個
AnimationDrawabledF對象來表示Frame動畫,然後通過addFrame 方法把每一幀要顯示的內容添加進去,並設定播放間隔時間,本例子中間隔時間為5S,
最後通過start 方法就可。
以播放這個動畫了,同時還可以通過 setOneShot方法設定是否重複播放。
package xiaosi.bu;import android.app.Activity;import android.graphics.drawable.AnimationDrawable;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;public class TupianActivity extends Activity { /** Called when the activity is first created. */private Button start = null;private Button stop = null;private ImageView image = null;private AnimationDrawable animationDrawable = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); start = (Button)findViewById(R.id.start); start.setOnClickListener(new StartListener()); stop = (Button)findViewById(R.id.stop); stop.setOnClickListener(new StopListener()); image = (ImageView)findViewById(R.id.imageview); animationDrawable = new AnimationDrawable(); for(int i =0;i<8;i++){ //第一個 就是我們的資源名稱(圖片名) //第二個 就是我們存放圖片的檔案夾drawable //第三個 包名也可以用Context的getPackageName返回應用程式的包名 int id = getResources().getIdentifier( "a"+i, "drawable", "xiaosi.bu"); System.out.println("ID:" + id); animationDrawable.addFrame(getResources().getDrawable(id), 2000); } //設定手否重複播放,false為重複 animationDrawable.setOneShot(false); image.setImageDrawable(animationDrawable); } private class StartListener implements OnClickListener{public void onClick(View v){animationDrawable.start();} } private class StopListener implements OnClickListener{public void onClick(View v){animationDrawable.stop(); } }}
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <Button android:id="@+id/start" android:text="Start" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/stop" android:text="End" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> <ImageView android:id="@+id/imageview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scaleType="fitXY" android:background="#ffffff" /> </LinearLayout>
原始碼:點擊開啟連結