difference between fragmentTransaction.add and fragmentTransaction.replace

前端 未结 2 1359
你的背包
你的背包 2020-12-14 01:14

What I already known is:

after fragmentTransaction.replace(), current fragment\'s onStop() function will be called while fragmentTran

2条回答
  •  天命终不由人
    2020-12-14 01:52

    Two choices

    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]

    Relevant Link:

    Check this Demo project for better understanding.

提交回复
热议问题