When to use the attach and detach methods of Fragm

2019-01-16 07:06发布

问题:

I just went through the documentation of the attach() and detach() methods of FragmentTransaction:

attach(): Re-attach a fragment after it had previously been detached from the UI with detach(Fragment). This causes its view hierarchy to be re-created, attached to the UI, and displayed.

Well, what does that mean?

  1. More specifically, I saw an example:

    mMapFragment = new MapFragment();
    ft.beginTransaction(mMapFragment)
      .attach()
      .add(R.id.container, mMapFragment)
      .commit();
    

    I deleted the attach() and tried again: I did not notice any difference. What does the attach do in this example? What is the difference compared to this:

    ft.beginTransaction()
      .add(R.id.container, mMapFragment)
      .commit();
    
  2. In case the example above is not good enough to show the difference... I just want to know when do we need to call the attach() and detach() explicitly? It would be better if you can explain the difference with respect to add/remove/replace.

回答1:

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 when it is put on the back stack: the fragment is removed from the UI, however its state is still being actively managed by the fragment manager. When going into this state its view hierarchy is destroyed.

Remove

Remove an existing fragment. If it was added to a container, its view is 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 optionally also have its view (if Fragment.onCreateView returns non-null) into a container view of the activity.

Attach

Re-attach a fragment after it had previously been deatched from the UI with detach(Fragment). This causes its view hierarchy to be re-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.