Adding and removing Fragments during runtime
Defining a Fragment in the layout, as we did in the previous recipe, is known as a static Fragment and cannot be changed during runtime. Rather than using the <fragment>
element, we will create a container to hold the Fragment, then create the Fragment dynamically in the Activity's onCreate()
method.
The FragmentManager
provides the APIs for adding, removing, and changing Fragments during runtime using a FragmentTransaction
. A Fragment transaction consists of:
Starting a transaction
Performing one or multiple actions
Committing the transaction
This recipe will demonstrate the FragmentManager
by adding and removing Fragments during runtime.
Getting ready
Create a new project in Android Studio and call it: RuntimeFragments
. Use the default Phone & Tablet options and select the Empty Activity option when prompted for the Activity Type.
How to do it...
To demonstrate adding and removing Fragments, we first need to create the Fragments, which we will...