My experiments with Headless Fragments
Ghanshyam Bhatt

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 RecyclerView.

As you can guess, the setup was quite complex and with Tabs involved, I needed a way to maintain:

  1. the list data itself
  2. vertical scroll position
  3. horizontal scroll position (for each child RecyclerView)

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.

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.