据我所知(并不一定正确),当应用程序完成对Drawables的使用时,它们通常会被正确地从内存中删除。然而,Bitmaps需要手动回收,并且有时甚至需要编写特殊的类来正确处理它们。我的问题是,在内存和泄漏方面,是否更有益于仅使用Drawables,就像这样:
myView.setBackgroundDrawable(getResources().getDrawable(R.drawable.my_image));
myView1.setBackgroundDrawable(getResources().getDrawable(R.drawable.my_image1));
myView2.setBackgroundDrawable(getResources().getDrawable(R.drawable.my_image2));
不是使用位图这样的东西:
Bitmap tmpBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
myView.setImageBitmap(tmpBitmap);
tmpBitmap.recycle();
tmpBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image1);
myView1.setImageBitmap(tmpBitmap);
tmpBitmap.recycle();
tmpBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image2);
myView2.setImageBitmap(tmpBitmap);
tmpBitmap.recycle();
当然,我也读到过必须小心Bitmap的recycle()方法,因为它们可能在仍在使用时被移除?似乎这些问题以不同形式不断出现,但我无法从任何人那里得到直接的答案。有人建议在每次使用后重用Bitmap并回收,而其他人建议使用Drawables和unbindDrawables()方法(这是我一直在使用的):
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
非常感谢能提供任何有用的见解。