我正在创建自己的 SlideShow 活动,其中有一个 ImageView,每次用户单击下一个或上一个时,我都会用正确的图像填充它。
这些图像虽然很大,但当我浏览其中的几个时,我得到一个 OutofMemory 可能是由于我的错误导致的内存泄漏。
问题是,每次调用新图像时,我都会尝试将前一个位图设为空,以便对其进行垃圾收集,但无济于事。
我在这里错过了什么吗?
我附上了我的活动的非常简单的代码:
public class SlideShowActivity extends Activity {
private static final String LOG_TAG = SlideShowActivity.class.getSimpleName();
private Bitmap currentBitmap;
private Bitmap mDefaultBitmap;
private ImageView imageView;
private ImageButton buttonPrev;
private ImageButton buttonNext;
private int currentImageIndex;
private String imguri[] = { "ruta1/imagen1.jpg", "ruta1/imagen2.jpg", "ruta1/imagen3.jpg", "ruta1/imagen4.jpg", "ruta1/imagen5.jpg", "ruta1/imagen6.jpg" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slideshow);
mDefaultBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.noimage);
imageView = (ImageView) findViewById(R.id.imageViewCurrentImage);
buttonPrev = (ImageButton) findViewById(R.id.imgbuttonprev);
buttonNext = (ImageButton) findViewById(R.id.imgbuttonnext);
currentImageIndex = 0;
setCurrentImage(currentImageIndex);
buttonPrev.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
currentImageIndex--;
if(currentImageIndex < 0)
currentImageIndex = imguri.length-1;
setCurrentImage(currentImageIndex);
}
});
buttonNext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
currentImageIndex++;
if(currentImageIndex == imguri.length)
currentImageIndex = 0;
setCurrentImage(currentImageIndex);
}
});
}
private void setCurrentImage(int idx) {
currentBitmap = null;
imageView.setImageBitmap(null);
try {
currentBitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeStream(getAssets().open(imguri[idx])),800, 480, true);
imageView.setImageBitmap(currentBitmap);
} catch (IOException e) {
Log.d(LOG_TAG, "No se pudo abrir el recurso" + imguri[0]);
imageView.setImageBitmap(mDefaultBitmap);
}
}
}