Fragment shared element transition with add() instead of replace()?
Asked Answered
S

3

44

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? Thanks

@Override
public void onClick(View v) {
    setSharedElementReturnTransition(TransitionInflater.from(getActivity())
        .inflateTransition(android.R.transition.move));

    FragmentB secondFragment = new FragmentB();
    secondFragment.setSharedElementEnterTransition(TransitionInflater.from(getActivity())
        .inflateTransition(android.R.transition.move));

    getFragmentManager().beginTransaction()
        .add(R.id.container, secondFragment)
        .addToBackStack(null)
        .addSharedElement(imageView, imageView.getTransitionName())
        .commit();
}
Station answered 25/3, 2015 at 15:25 Comment(1)
The other fragment you are using is a child fragment ?Potman
T
6

Try this

getSupportFragmentManager().beginTransaction() 
                .addSharedElement(myImage, "mytransition") 
                .add(R.id.recycler_view_container, myFragment2) 
                .hide(myFragment1)  
                 commit(); 

worked for me

Truett answered 24/3, 2021 at 21:45 Comment(0)
S
4

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:

https://github.com/Kisty/FragmentTransitionExample

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

https://www.youtube.com/watch?v=CPxkoe2MraA

Strop answered 2/10, 2016 at 8:35 Comment(1)
This hack seems to work for ImageViews but it is a little complicated if the view is a viewgroup itself.Whallon
I
0

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)
            .detach(currentFragment)
            .add(intoContainerId, newFragment, withTag)
            .commit();
Imitable answered 14/2, 2019 at 8:5 Comment(1)
this makes the view in background go from UI, which destroys the whole purpose of adding the fragment instead of replacing it in first place.Whallon

© 2022 - 2024 — McMap. All rights reserved.