I am working with a UI using tabs in the ActionBar. When switching between tabs I am currently managing the Tab click events in my Activity and am calling attach and detach as needed using FragmentManager.
Each time a Fragment is attached I am going through the full lifecycle and creating a new view and loading all my data over again. I am using the given Bundle in onSaveInstanceState and onActivityCreated to update gui elements (mainly the scroll position of a list).
This is working OK, but has lots of overhead. In my case the list may have 300 or so records and there is a noticeable delay when switching between tabs.
In an effort to speed things up I am now saving the root view in onCreateView as a class variable. Then when onCreateView is called again as a result of the fragment being attached I test for a non null value for my root view and return it instead of re-inflating the view. This saved view still has the appropriate data set and I also bypass loading the data in this case. Of course I still need to fully rebuild the view and data if the Fragment is destroyed by OS while in the background.
My question is if this is a valid approach? I don’t see a downside to it unless there are memory issues to worry about.
It’s not the best approach, and here’s why:
When you create the root view the first, all views are inflated using the
Activity‘s context. If thisActivityever gets destroyed, and then you attempt to reattach theFragmentto a new instance of thisActivity, you will have issues.Secondly, it’s a terrible use of memory to have a fully inflated root view sitting around when it’s not being used. Now, the records you mention are not stored in any
View, but rather your list view has a reference to an adapter you created, which is keeping that adapter in memory along with your views. That is a lot of data to just have sitting around.Now to properly give you a recommendation, you ultimately have to draw a line between memory usage and performance, keeping in mind that if you plan to make this app public, there are a LOT of inferior hardware devices.
One option is what you have already done, which is to make use of the
savedInstanceStatevariable when being detached. You can try putting your 300 records in thisBundleand see how that performs. If the data is a class you have created, implement theParcelableinterface (see documentation to know how to properly implement this) and store it in theBundle, and then retrieve it later and create a new adapter. I would highly advise against keeping references toViews between attachments.