Can a ListView contain Fragments

I’d say this is not possible to do as putting a fragment in a ListView would mean the fragment can be multiplied across multiple containers. When you use the FragmentManager to create a fragment, it is tagged with an identifier, making it simple to reload and rearrange on orientation and other configuration changes. It also encourages uses across multiple device configs.

A Fragment is really a subset of an Activity. Would you ever have an Activity as part of a list? Definitely not (should be the answer!)!!!

Moreover, it is not very useful to attach() and detach() a fragment continuously as they move in and out of view (cells get recycled). These are all expensive operations that a ListView shouldn’t deal with. Lists should scroll quickly.

From the conversation on the comments, I can see you want to achieve nice code with a good separation of view setup code and adapter in the Activity. Do so with either:

  1. Override the View class and do your custom drawing and setup there.
  2. Create a new class, in which you supply a context and data set required for it to get you back the view a list needs to show – this is what I usually do.
  3. Have a Utils class to build your video elsewhere (silly).

Just don’t use Fragments in Lists. Not the use case they are aiming for. HTH.

Leave a Comment