Ungureanu Liviu
Ungureanu Liviu

Reputation: 4124

How to cache views in Android?

I'm building an app which generate some labels and views dynamically. I defined how my "custom view" should look in a xml layout and from code I inflate this layout.

Because the inflated layout will be always the same, I want to make this step just one time. After I have the layout, I want to cache it and use it next time when I will need it.

The problem is that if I put my inflated layout in cache (in a hashmap by example) and add it to a parent layout, next time when I try to add it again (this time I will get the layout from cache) the system says that my layout already have a parent.

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

Added some 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);

Upvotes: 7

Views: 5145

Answers (1)

Sherif elKhatib
Sherif elKhatib

Reputation: 45942

You can not actually do this. I am quoting 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 each time because you need 5 different instances of this textbox. If you wish not to inflate, you should find a way to copy the layout that is already created which will not help improve because copying is "costly" as well.

As a matter of fact, just to make it clear, inflating the view does not undergo XML parsing (just in case you think so), it is compiled code and, hence, the fact that putting an effort in implementing a way to create a copy of your view is pointless.

Bottom-line: Stick to inflation.

Upvotes: 12

Related Questions