How to cache views in Android?

I am creating an application that generates some labels and views dynamically. I determined how my “custom view” should look in the xml layout and from the code I inflate this layout.

Since the bloated layout will always be the same, I want to take this step only once. After I have the layout, I want to cache it and use it the next time I need it.

The problem is that if I put my bloated layout in the cache (in the hash file for example) and add it to the parent layout, the next time I try to add it again (this time I get the layout from the cache) the system says that my layout already has a parent.

Do you know any method to detach a child view from a parent without deleting the child view?

Added code:

    private static HashMap<String, LinearLayout> mComponentsCache;

// inflate and add the layout in cache
layout = (LinearLayout)mLf.inflate(R.layout.form_textbox, mHolder, false);
mComponentsCache.put(FormFieldType.TYPE_TEXT, layout);
+5
source share
1 answer

You cannot do this. I quote your comment

I want to do it in this way because is no point to re-inflate the same view which was already inflated. As an example I have to show 5 textboxes which have the same layout but different content.

You will have to inflate every time because you need 5 different instances of this text box. If you do not want to bloat, you must find a way to copy the created layout, which will not improve, because copying is also "expensive".

In fact, just to make it clear, inflating a view is not parsed by XML (just in case you think so), it is compiled code and therefore the fact that making an effort to implement a path to create a copy of your Submission is pointless.

Bottom line: stick to inflation.

+9
source

All Articles