将图像加载到我的应用程序中时出现内存不足异常。我集成了毕加索来加载图像,但下面的代码不适用于 AnimationDrawable 的动画列表。动画为空:
Picasso.with(this).load(R.drawable.qtidle).into(qtSelectButton);
qtIdleAnimation = (AnimationDrawable)qtSelectButton.getDrawable();
if (qtIdleAnimation != null)
qtIdleAnimation.start();
AnimationDrawable可以工作,如果我在没有毕加索的情况下使用此代码:
qtIdleAnimation = new AnimationDrawable();
qtIdleAnimation.setOneShot(false);
for (int i = 1; i <= 7; i++) {
int qtidleId = res.getIdentifier("qtidle" + i, "drawable", this.getPackageName());
qtIdleAnimation.addFrame(res.getDrawable(qtidleId), 100);
}
qtSelectButton.setImageDrawable(qtIdleAnimation);
if (qtIdleAnimation != null)
qtIdleAnimation.start();
但此代码会导致内存不足异常。是否可以使用毕加索加载动画列表?
>毕加索不能直接将xml
文件中定义的动画列表加载到视图中。但自己模仿毕加索的基本行为并不难:
1. 像您一样以编程方式定义和启动动画,但在 AsyncTask 中以避免内存不足异常
Resources res = this.getResources();
ImageView imageView = findViewById(R.id.image_view);
int[] ids = new int[] {R.drawable.img1, R.drawable.img2, R.drawable.img3};
创建 AsyncTask 的子子:
private class LoadAnimationTask extends AsyncTask<Void, Void, AnimationDrawable> {
@Override
protected AnimationDrawable doInBackground(Void... voids) {
// Runs in the background and doesn't block the UI thread
AnimationDrawable a = new AnimationDrawable();
for (int id : ids) {
a.addFrame(res.getDrawable(id), 100);
}
return a;
}
@Override
protected void onPostExecute(AnimationDrawable a) {
// This will run once 'doInBackground' has finished
imageView.setImageDrawable(a);
if (a != null)
a.start();
}
}
然后运行任务以将动画加载到 ImageView 中:
new LoadAnimationTask().execute()
2. 如果可绘制对象大于视图,请仅以所需分辨率加载可绘制对象来节省内存
而不是直接添加可绘制对象:
a.addFrame(res.getDrawable(id), 100);
添加它的缩小版本:
a.addFrame(new BitmapDrawable(res, decodeSampledBitmapFromResource(res, id, w, h));
其中w
和h
是视图的尺寸,decodeSampledBitmapFromResource()
是 Android 官方文档中定义的方法(高效加载大位图(