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: ...

Get Android Application Development Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.