Listen when a shared element is back on original Fragment

Viewed 85

Hello Android community,

I have a very simple app, composed of two fragments A & B and there is a shared element between those two fragments.

When I open Fragment B, the transition is working well, and I'm able to listen when the element has finished the transition. However, when I pop FragmentB, I'd like FragmentA to be informed that the return transition is over.

I made a project example here: https://github.com/JulienDev/shared_element_listener

As you can see, I've tried many different things without success.

Do you know if that's something possible?

Thank you so much :)

1 Answers

I think issue has been solved. First change goToB() method as below :

fun goToB(view: View) {
supportFragmentManager.beginTransaction()
.addSharedElement(view, "view_transition")
.replace(findViewById<ViewGroup>(R.id.preorder_content).id, FragmentB())
//.addToBackStack("")
.disallowAddToBackStack()    // Prevent from adding this fragment to Back stack
.commit()
}

Right now, we are inside Fragment B. If back button is clicked now, then I have used call back to handle it programmatically by adding callback in Fragment B. Like :

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

val transitionView = requireView().findViewById<View>(R.id.view_transition)
transitionView.setOnClickListener {
       (activity as MainActivity).goToC(transitionView)
   }
// This callback will only be called when Fragment B is at least Started.
requireActivity().onBackPressedDispatcher.addCallback(this) {
        (activity as MainActivity).goFromBToA(transitionView)
    }
}

I have put another method in Activity.

fun goFromBToA(view: View){
    supportFragmentManager.beginTransaction()
        .addSharedElement(view, "view_transition")
        .replace(findViewById<ViewGroup>(R.id.preorder_content).id, FragmentA())
        .disallowAddToBackStack()
        .commit()
}

Now I can see transition end log when pop up to Fragment A from B.

Related