核心思想:复用图片资源
功能实现:定制AnimationDrawable
贴代码
public class CustomAnimationDrawable extends AnimationDrawable {
public interface CallBack {
void onEnd(AnimationDrawable animationDrawable);
}
private CustomAnimationDrawable.CallBack callback;
private int mCurrentIndex = -1;
private Map<Integer, Integer> res = new HashMap<Integer, Integer>();
private List<Integer> ids = new ArrayList<Integer>();
private LruCache<Integer, BitmapDrawable> cache = ImageCache.CACHE;
private Resources resources;
public CustomAnimationDrawable(Resources resources) {
this.resources = resources;
}
int pageIndex = 0;
@Override
public void start() {
super.start();
mCurrentIndex = 0;
}
@Override
public void stop() {
// TODO Auto-generated method stub
super.stop();
mCurrentIndex = 0;
}
@Override
public void addFrame(Drawable frame, int duration) {
// TODO Auto-generated method stub
super.addFrame(frame, duration);
}
public void addFrame(int frame, int duration) {
// TODO Auto-generated method stub
res.put(frame, duration);
ids.add(frame);
}
@SuppressWarnings("deprecation")
public void init() {
for (int i = 0;i < ids.size(); i++) {
pageIndex = i;
if (null==cache.get(ids.get(i))||cache.get(ids.get(i)).getBitmap().isRecycled()) {
Options opts = new Options();
opts.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeResource(resources, ids.get(i), opts);
BitmapDrawable framed = new BitmapDrawable(bitmap);
addFrame(framed, res.get(ids.get(i)));
cache.put(ids.get(i), framed);
}else{
addFrame(cache.get(ids.get(i)), res.get(ids.get(i)));
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
if (cache.size() <= 0||getNumberOfFrames()<=0) {
init();
}
super.run();
if (isLast()) {
System.gc();
}
}
private boolean isLast() {
if (getNumberOfFrames() <= 1) {
if (null != callback) {
callback.onEnd(this);
}
return true;
}
if (mCurrentIndex != -1) {
mCurrentIndex++;
if (mCurrentIndex >= getNumberOfFrames() - 1) {
if (null != callback) {
callback.onEnd(this);
}
return true;
}
return false;
}
int currentIndex = 0;
Field field = null;
try {
field = this.getClass().getSuperclass().getDeclaredField("mCurFrame");
}
catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
field.setAccessible(true);
try {
currentIndex = field.getInt(this);
mCurrentIndex = currentIndex;
}
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
field.setAccessible(false);
if (currentIndex >= getNumberOfFrames() && !isOneShot()) {
if (null != callback) {
callback.onEnd(this);
}
return true;
}
return false;
}
public void setCallback2(CallBack callback) {
this.callback = callback;
}
}