Hi Ghanshyam Bhatt,
Those are some great insights. I happened to use a Headless
Fragment in one my projects too. Didn’t have the luxury to use an architecture like MVP.
In the project I worked on, there were a lot of Tabs. Each having a list that was horizontally scrollable. A.k.a. nested
As you can guess, the setup was quite complex and with Tabs involved, I needed a way to maintain:
- the list data itself
- vertical scroll position
- horizontal scroll position (for each child
That was a lot of data!
Initially I was saving all of this in
onSaveInstanceState(). It seemed to work perfectly at the time. But once I bumped the target SDK to Android Nougat, all hell broke loose!
Every time I added this data to my Fragment’s
onSaveInstanceState(), it threw a TransactionTooLarge exception.
I updated Nexus 5X to Android N, and now when I install the app (debug or release) on it I am getting…stackoverflow.com
Apparently, Android throws this exception when your Parcel size exceeds 1MB. Mine was at least 1.5MB per
Fragment (Tab). Ouch!
I didn’t want to be storing this data in the
Application class as it was already heavy.
Headless Fragments was my last resort. I decided to use that.
So now, there’s one Headless Fragment that holds the data for all Tabs. When one Tab is brought back into view, I restore it’s Fragment data via this Headless Fragment.
Although this solution seems to work like a breeze, I personally don’t think this is such a clean solution. Or in other words, if this is even the right way to do it.
However, the end result is that those TransactionTooLarge exceptions stopped occuring.
But, like you said, I’m positive the Architecture Components should give us a better approach.
Architecture components helps us manage UI components lifecycle and persist data of configuration changes.Let’s see how to use its 3 components to build a sample app…blog.iamsuleiman.com