I like the approach of FragmentFactory
, which makes it possible to pass dependencies to a fragment in a constructor.
I'd like to use a custom FragmentFactory
together with a FragmentStatePagerAdapter
.
I'm hosting the view pager in an activity. I can create a custom fragment factory and assign it to the activity using
supportFragmentManager.fragmentFactory = CustomFragmentFactory()
I can then use supportFragmentManager
to initialize my FragmentStatePagerAdapter
.
That's fine so far.
My problem is that my fragments within the view pager show data dependent on the position.
Let's say I have a list items
and ItemFragment
, which is shown in a view pager showing items[position]
, hence have a constructor like this:
class ItemFragment(val item: Item) : Fragment()
How must I implement the CustomFragmentFactory
and FragmentStatePagerAdapter
's getItem(position: Int)
function to achieve a safe equivalent of this:
override fun getItem(position: Int) = ItemFragment(items[position])
FragmentFactory
doesn't provide a way to pass dynamic data. Hence, FragmentFactory
doesn't work in this scenario.
If you have dynamic arguments you have to pass the them the classic way using a bundle (or use an approach like Safe Args, which generates code using a bundle).
This article talks about the exact same scenario:
The limitation of using FragmentFactory is that we can’t pass dynamic arguments to it.
Let’s say we have a ViewPager that display’s two instances of the same mainFragment but with different textToDisplay values then this won’t be possible using the fragmentFactory implementation.