Henrique
Henrique

Reputation: 5011

Does Android cache drawable resources loaded in xml layout files?

I have a ViewPager which loads lots of fragments (+20). Each one of these fragments is just an instance of one single fragment, and the only thing that changes is the content of each one. The UI for this fragment has, among other widgets, 4 different ImageViews which all load the same resource drawable but are of course located in different parts of the UI.

Now, if we take into account that I might have for example 20 fragments with this scheme, we're talking about 80 (20*4) ImageViews which would all load the same drawable.

So, that made me wonder, does Android cache in any way resources that are loaded from xml layouts? If not, is there a better option then simply loading this drawable in code, caching it and attaching it programmatically to their corresponding ImageView every time a new instance of this fragment gets created?

Thanks.

Upvotes: 9

Views: 7487

Answers (3)

Henrique
Henrique

Reputation: 5011

Just a summary of the blog entry provided in the accepted answer, so people don't have to read the whole blog. In the example in the blog post, the author talks about creating various Buttons, which will eventually all share the same drawable:

This way, all buttons across all applications share the same bitmap, which saves a lot of memory.

So yes, apparently Android does optimize resources loaded.

Upvotes: 4

bassgeneration
bassgeneration

Reputation: 1

here is how you change the image of the imageview programaticaly :

        Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.your_drawable);
    your_imageView.setImageBitmap(bitmap);

hope this help ,you can find more tutoriel hereclick here

Upvotes: -4

Niko
Niko

Reputation: 8153

Android does have some kind of recycling management with Drawable component. I have noticed this very clear when using same resources for Drawables and using ColorFilter with them, and I have ended seeing wrong color with previously created drawable which hasn't been visible yet in UI.

I would say your approach is OK.

In this post Romain explains that Drawables share some information, for example the Bitmap they are drawing: http://www.curious-creature.org/category/android/page/2/

Upvotes: 10

Related Questions