Dynamic fragments
So far, you’ve only seen fragments added in XML at compile time. Although this can satisfy many use cases, you might want to add fragments dynamically at runtime to respond to the user’s actions. This can be achieved by adding ViewGroup
as a container for fragments and then adding, replacing, and removing fragments from ViewGroup
.
This technique is more flexible as the fragments can be active until they are no longer needed and then removed, instead of always being inflated in XML layouts as you have seen with static fragments. If three or four more fragments are required to fulfill separate user journeys in one activity, then the preferred option is to react to the user’s interaction in the UI by adding/replacing fragments dynamically.
Using static fragments works better when the user’s interaction with the UI is fixed at compile time and you know in advance how many fragments you need. For example, this would be the case for selecting...