据我了解(不是我是正确的)当应用程序完成时,Drawables 通常会正确地从内存中删除。然而,位图需要手动回收,有时甚至需要编写一个特殊的类来正确处理它们。我的问题是,关于内存和泄漏,像这样简单地坚持使用 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();
我当然也读过,您必须小心位图上的 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();
}
}
不过,任何适用的见解将不胜感激。谢谢