简体   繁体   English

Android BitmapDrawable回收/重用

[英]Android BitmapDrawable recycling/re-use

In the code below I've got two bitmaps (I omitted the code for creating them as that's not relevant to my question) and I also have an ImageView in my layout. 在下面的代码中,我有两个位图(我省略了创建它们的代码,因为这与我的问题无关)而且我的布局中也有一个ImageView。 I make the ImageView display the first bitmap as a drawable, and then make it display the second bitmap, again as a drawable. 我将ImageView显示为第一个位图作为drawable,然后使其显示第二个位图,再次作为drawable。

I'm aware that bitmaps can be recycled, my question is related to the "new BitmapDrawable" part, as I can't figure out exactly what a BitmapDrawable is. 我知道位图可以回收,我的问题与“新的BitmapDrawable”部分有关,因为我无法弄清楚BitmapDrawable到底是什么。 Is it just a reference or does it use up memory each time one is created? 它只是一个引用,还是每次创建时都会耗尽内存? In other words, does the BitmapDrawable I create for bitmap1 need to be deleted/recycled before I create another BitmapDrawable for bitmap2? 换句话说,在为bitmap2创建另一个BitmapDrawable之前,我为bitmap1创建的BitmapDrawable是否需要删除/回收?

Thanks. 谢谢。

Bitmap bitmap1,bitmap2;

...assume bitmap1 and bitmap2 contain valid bitmaps...

// get imageview
ImageView iv = (ImageView)findViewById(R.id.my_imageview);

// make the imageview display bitmap1
iv.setImageDrawable(new BitmapDrawable(getResources(),bitmap1));        

// now make the imageview display bitmap2
iv.setImageDrawable(new BitmapDrawable(getResources(),bitmap2));        

You should keep bitmaps as long as you need them. 只要你需要它们,你应该保留位图。 It is costly to create new bitmaps. 创建新位图的成本很高。 GC will fire if enough memory not available and your app will stall for that time. 如果没有足够的内存,GC将会触发,您的应用程序将停止运行。

See this for efficiently displaying bitmaps http://developer.android.com/training/displaying-bitmaps/index.html 有效显示位图,请参阅此内容http://developer.android.com/training/displaying-bitmaps/index.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM