Difference between add() and replace() in FragmentTransaction in Android

Rohit Singh
2 min readSep 23, 2019

--

This is a re-post of an answer I wrote on Stackoverflow.

A picture is worth a thousand words

Here is the picture:

and a thousand words…

Let’s say you have a fragment container.
And, your task is to add a fragment into the container.

You can do this by calling any of the following methods

1) add(containerId,fragment)
2) replace(containerId,fragment)

But both methods differ in behavior !!!

Although both methods will add your fragment into the fragment container, their innards(internal working) differ based on the two possible states of the fragment container.
When fragment container
1) does not have any fragment in it.
2) already have one or multiple fragments attached to it.

Let’s see what happens when we call add() and replace() method.

Case 1: When there is no fragment attached in a container

In this case, both methods will add the fragment to the container. So they will produce same effect.

Case 2: When the fragmentContainer already has fragment/fragments

add(): adds the new fragment on the top another fragment
replace(): removes everything then adds the new fragment

Example
So suppose the Fragment container has fragments[A->B->C].
Now you want to add a new fragment D.
add() method result will be [A->B->C->D]
replace() method result will be [D]

Putting up content takes a lot of time and effort 😓.
👏 clap 👏 If you think you learned something from this article.
You can find me on Stackoverflow,Github,and,on Linkedin.
Give feedback and feel free to correct mistakes.

Relevant Link:

Check this Demo project for better understanding.

Read More:

What is addToBackStack in Fragment

--

--

Rohit Singh
Rohit Singh

Written by Rohit Singh

Android Developer | Arizona State University | NASA Psyche Research Aide

No responses yet