Defining a Fragment in the layout, as we did in the previous recipe, is known as a static Fragment, which doesn't allow the fragment to 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 the following:
- Starting a transaction
- Performing one or multiple actions
- Committing the transaction
This recipe will demonstrate the Fragment Manager by adding and removing Fragments during runtime.
Create a new project in Android Studio and call it: RuntimeFragments
. Use the default Phone & Tablet
option and select Empty Activity
on the Add an Activity to Mobile
dialog.