Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache views in Android?

Tags:

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);
like image 902
Ungureanu Liviu Avatar asked Aug 31 '12 07:08

Ungureanu Liviu


People also ask

How do you save cache on Android?

Saving Cache Files To get the internal storage cache directory, use the getCacheDir() method. This returns a File object that represents your app's internal storage directory. You can access the external cache directory with the similarly named getExternalCacheDir().

What is caching in Android Studio?

The Android Studio system cache is what gets invalidated when you click “Invalidate Caches / Restart”. Android Studio uses it to store information about the project structure, and it's unrelated to Gradle and the build process. Other Jetbrains IDEs use a similar cache.


1 Answers

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.

like image 159
Sherif elKhatib Avatar answered Oct 10 '22 15:10

Sherif elKhatib