Fragment management

Add dependency to use fragments

Add dependency
val fragment_version = "1.3.4"

// Java language implementation
implementation("androidx.fragment:fragment:$fragment_version")
// Kotlin
implementation("androidx.fragment:fragment-ktx:$fragment_version")

FragmentActivity is a base class for activities that want to use fragments. For example, AppCompatActivity class is direct subclass.

Activity can have list of fragments. Also each fragment can have its own list for child fragments.

FragmentManager class is responsible for performing actions on your app's fragments, such as adding, removing, or replacing them, and adding them to the backstack. You can get it with the getSupportFragmentManager() method of FragmentActivity.

Inside a fragment, you can get a reference to the FragmentManager that manages the child fragments with getChildFragmentManager() method. If you need to access its host FragmentManager, you can use getParentFragmentManager() method.

FragmentTransaction represents an operation on to a list of fragments. You can save transaction in the fragment backstack.

A FragmentManager.BackStackEntry interface represent an entry of the fragment backstack, as created with FragmentTransaction.addToBackStack(). Entries can later be retrieved with FragmentManager.getBackStackEntryAt().

You should never hold on to a BackStackEntry object; the identifier as returned by getId() is the only thing that will be persisted across activity instances.

FragmentManager

Add root fragment
class ExampleActivity : AppCompatActivity(R.layout.example_activity) {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // set our fragment as root fragment at first time  
        if (savedInstanceState == null) {

            val bundle = bundleOf("some_int" to 0)
            
            supportFragmentManager.commit {
                setReorderingAllowed(true) // You should always use it in transaction
                add<ExampleFragment>(R.id.fragment_container_view, args = bundle)
            }
        }
    }
}
method description
addFragmentOnAttachListener(l) Add a listener to handle the event of attaching a new fragment to this FragmentManager.
addOnBackStackChangedListener(l) Add a new listener for changes to the fragment back stack.
beginTransaction() Start a series of edit operations on the Fragments associated with this FragmentManager.
executePendingTransactions() After a FragmentTransaction is committed with FragmentTransaction.commit(), it is scheduled to be executed asynchronously on the process's main thread.
findFragment(view) Find a fragment associated with the given view.
findFragmentById(id) Finds a fragment that was identified by the given id either when inflated from XML or as the container ID when added in a transaction.
findFragmentByTag(tag) Finds a fragment that was identified by the given tag either when inflated from XML or as supplied when added in a transaction.
getBackStackEntryAt(ind) Return the BackStackEntry at given index in the back stack; entries start index 0 being the bottom of the stack.
getBackStackEntryCount() Return the number of entries currently in the back stack.
getFragments() Get a list of all fragments that are currently added to the FragmentManager.
popBackStack() Pop the top state off the back stack.
popBackStack( name, flags) Pop the last fragment transition from the manager's fragment back stack.
saveBackStack( name) Save the back stack.
restoreBackStack( name) Restores the back stack previously saved via saveBackStack(String).

FragmentTransaction

Add fragments with animations
fragmentManager.beginTransaction()
    .setCustomAnimations(enter1, exit1)
    .add(MyFragmentClass, args, tag1) // this fragment gets the first animations
    .setCustomAnimations(enter2, exit2)
    .add(MyFragmentClass, args, tag2) // this fragment gets the second animations
    .commit()
method description
add(viewId, f, tag) Add a fragment to the activity state, where:
  • viewId - optional identifier of the container this fragment is to be placed in. If 0, it will not be placed in a container.
  • tag - optional tag name for the fragment, to later retrieve the fragment with FragmentManager.findFragmentByTag(String)
remove(f) Remove an existing fragment.
replace(viewId, f, tag) Replace an existing fragment that was added to a container.
hide(f) Hides an existing fragment. This is only relevant for fragments whose views have been added to a container, as this will cause the view to be hidden.
show(f) Shows a previously hidden fragment. This is only relevant for fragments whose views have been added to a container, as this will cause the view to be shown.
setCustomAnimations( enterId, exitId) Set specific animation resources to run for the fragments that are entering and exiting in this transaction. These animations will not be played when popping the back stack.
addToBackStack(name) Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.
commit() Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.
commitAllowingStateLoss () Like commit() but allows the commit to be executed after an activity's state is saved. This is dangerous because the commit can be lost if the activity needs to later be restored from its state, so this should only be used for cases where it is okay for the UI state to change unexpectedly on the user.
commitNow () Commits this transaction synchronously. Any added fragments will be initialized and brought completely to the lifecycle state of their host and any removed fragments will be torn down accordingly before this call returns.