Main menu

Fragments inside fragments inside fragments

Don't know about you, but when programming I always try to think ahead and make my code future proof by thinking how some concept A will behave when fed with data B. So what exactly were Android engineers thinking when they invented fragments and didn't provide any mechanisms to manage fragments inside fragments?

That's right - first they give you a nice concept (I call it nice mainly because when creating a new fragment I don't need to go back to AndroidManifest.xml, whatever this damn file does) and then they say: "You want to have fragments in fragments? Eeerrrrmmm... We didn't think about THAT". Fortunately they had a lot of time to fix it, unfortunately the solution is lame. And if you don't know it, you will spend countless hours trying to figure why your fragemnts don't appear, although in debugger they seem fully initialized.

And that's exactly what happened when I migrated a few of my ugly solutions to FragmentStatePagerAdapter.

XenoAmp main activity layout contains two fragment containers: one for main view and the other one, at the bottom - for playlist drawer. So one day I've decided I want to allow users drag playlist drawer not only up and down, but also left or right (like changing to another drawer). And this means I needed to substitute my drawer contents, which was a simple DragSortListView with ViewPager that holds multiple DragSortListViews. It's a bit like the good old deprecated Gallery, but creates a multitude of fragments to do its magic. In other words - my playlist drawer fragment was now containing a lot of fragments with playlists!

And guess what? Somewhere it worked, somewhere - it didn't! Exactly the same code! The place it didn't work was music row fragment (the one that shows when you tap album icon in music view), which in main view contains exactly same ViewPager with another set of playlists! When both "root" fragments were visible on screen (so: two fragment containers, each containing a single fragment, both of which contained a crowd of other fragments), switching between playlist was broken! It looked like PlaylistStatePagerAdapterForSheetRow returned null for newly created fragments!

I examined everything up to "root" containing fragment and ended here, in my MusicRowFragment onCreateView method:

adapterStron = new PlaylistStatePagerAdapterForSheetRow(getFragmentManager(), getIndex());

So to make long story short, oh mighty Flying Spaghetti Monster! Bless you for StackOverflow! Within minutes I discovered the ugly truth and fortunately the fix was simple, you have to use ChildFragmentManager not FragmentManager

adapterStron = new PlaylistStatePagerAdapterForSheetRow(getChildFragmentManager(), getIndex());

And guess what? Now it worked! Yes, Google. Thank you for elegant API!

FacebookG+TwitterRSS