When to use the attach and detach methods of FragmentTransaction When to use the attach and detach methods of FragmentTransaction android android

When to use the attach and detach methods of FragmentTransaction


I think it is better to have a look at definition of Detach and Remove in FragmentTransaction Documentation to understand what is going on.

Detach

Detach the given fragment from the UI. This is the same state as whenit is put on the back stack: the fragment is removed from the UI,however its state is still being actively managed by the fragmentmanager. When going into this state its view hierarchy is destroyed.

Remove

Remove an existing fragment. If it was added to a container, its viewis also removed from that container.

It means:

By detaching you only destroy the fragment View but keep its state in the fragment manager. However, by removing you will remove the fragment and its state from the fragment manager; in addition it will remove the fragment view if it was added to a UI container.So both of them destroy the fragment view, but detach keeps the fragment state in the fragment manager.


Now its time to have a look at attach and add.

Add

Add a fragment to the activity state. This fragment may optionallyalso have its view (if Fragment.onCreateView returns non-null) into acontainer view of the activity.

Attach

Re-attach a fragment after it had previously been deatched from the UIwith detach(Fragment). This causes its view hierarchy to bere-created, attached to the UI, and displayed.

It means:

After adding Fragment it will be added to activity state and its view will be added to defined Container view.But by attaching nothing will be displayed if fragment was not already added to UI. It just attaches to fragment manager. However if view was already added to a container in UI and detached after that, by attaching it will be displayed again in its container. Finally you can use attach and detach if you want to destroy fragment View temporarily and want to display and build its view on future without losing its state inside activity.