Reputation: 143
I am using FragmentStatePagerAdapter to create view pager for a list of objects. Each page is a fragment.
However, on that page, I am also using fragments to display some other data.
I got problem when doing this. I wonder can I put fragments in fragment. Or any other solutions to work this out?
Upvotes: 1
Views: 362
Reputation: 4556
I have used Fragments inside an Fragment in a project. The way I ended up doing is adding these inside fragments via code and using the fragment attached to the activity as a "proxy" for the other, so on the oncreateview() of the fragment you instantiate the inside fragments, ondestroyview() you remove the inside fragments and so on.
Upvotes: 0
Reputation: 75619
Nested fragments are not supported by current fragment implementation (it was answered by Diane, Android engineer as well here:
Nested fragments are not currently supported. Trying to put a fragment within the UI of another fragment will result in undefined and likely broken behavior.
But it does not mean it is not doable - it can be achieved, however requires writing some more code than just fragment. There's comment in same thread by other user:
I managed this by extending FragmentActivity, FragmentManager, and FragmentTransaction. Basic premise is extend DeferringFragmentActivity in my activities, providing same api so no other code changes. When I call getFragmentManager, I get an instance that DeferringFragmentManager, and when I call beginTransaction, I get a DeferredTransaction. This transaction stores POJOs with the called method and arguments. When commit is call, we look for any pending DeferredTransactions first. Once all transactions have been committed, we start a real transaction and run all the stored methods with args
In general - unless you are desperated, just redesign your layout.
Upvotes: 1
Reputation: 2014
Fragments cannot hold other fragments. It's not supported (errors with state)
Upvotes: 0