創建AnimationDrawable我assets
文件夾中找到幾個.png文件(我的動畫幀),比我他們在我Activity
的onCreate()
方法使用AssetManager
並填寫我的AnimationDrawable
與他們取。如開發指南中所述,無法在onCreate()
方法中啓動動畫,並且如果需要立即啓動動畫,則比我應該覆蓋onWindowFocusChanged()
方法。但即使在這樣的實現中,我的可繪製對象也不會出現在屏幕上。這裏是我的活動代碼:從資產
package org.example.Animation;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
private LinearLayout ll;
private ImageView image;
private AnimationDrawable ad;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ll = new LinearLayout(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-2, -2);
image = new ImageView(this);
ll.addView(image, lp);
setContentView(ll);
AssetManager am = getAssets();
ad = new AnimationDrawable();
StringBuilder sb= new StringBuilder("loader/loader-");
// Fetching frames from assets
for(int i = 1; i < 11; i++) {
sb.append(i);
sb.append(".png");
Log.d("DownloadImageTask", "Fetching image: " + sb.toString());
try {
Drawable d = Drawable.createFromStream(am.open(sb.toString()), null);
ad.addFrame(d, 500);
}
catch (IOException e) {
Log.d("ImageViewAdapter", "IOException: " + e.getMessage());
}
sb.delete(14, sb.length()); // 14 - is the index of first digit of frame
}
image.setBackgroundDrawable(ad);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
ad.start();
}
}
請告訴我什麼是錯在我的代碼?
P.S 請不要問我爲什麼我不使用XML文件。簡而言之,我的主要目標是避免使用R.java文件。