Home » Android » android – Fragment shared element transition with add() instead of replace()?

android – Fragment shared element transition with add() instead of replace()?

Posted by: admin April 23, 2020 Leave a comment


I am trying to make a shared element transition between fragments, everything works fine when using replace() to add the second fragment, however in the codebase add() is used a lot, but when using that, transition just skips to end values

Is it possible to have the transition between added fragments?

public void onClick(View v) {

    FragmentB secondFragment = new FragmentB();

        .add(R.id.container, secondFragment)
        .addSharedElement(imageView, imageView.getTransitionName())
How to&Answers:

since the system isnt going through the onPause from the first fragment its not going to happen. becuase when you add a new fragment, the new fragment comes on the top of the old fragment.

but you can fake it though you will have more code !

there is a sample below:


and a video not compeletely related but helps you to get the idea:



Try add .detach() method for FragmentTransaction.

    FragmentManager manager = activity.getSupportFragmentManager ();
    Fragment currentFragment = manager.findFragmentById (CONTAINER_ID); 
    int intoContainerId = currentFragment.getId ();
    manager.beginTransaction ()
            .setTransition (FragmentTransaction.TRANSIT_FRAGMENT_FADE)
            .addSharedElement(view, transitionName)
            .addToBackStack (withTag)
            .add(intoContainerId, newFragment, withTag)