Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared transition with getChildFragmentManager() not working but working with getFragmentManager()

I implement fragments as below:

  1. Activity to hold parent fragment. Uses getSupportFragmentManager() to add Parent fragment.
  2. In parent fragment I use getChildFragmentManager() and transaction to replace childFragment.
  3. In childFragment I again call childFragment and so on....
  4. Everything work fine except shared transition.'
  5. If I use getFragmentManager() instead of getChildFragmentManager() then there is shared transition but then there is not concept of getChildFragmentManager().

The code sample looks like:

/*This code does not show animation*/
getChildFragmentManager()
                .beginTransaction()
                .addSharedElement(transitionView, ViewCompat.getTransitionName(transitionView))
                .replace(R.id.fragment_container, categoryDetailChildFragment)
                .addToBackStack(TAG)
                .commit();

and the code that shows animation is:

  getFragmentManager()
                .beginTransaction()
                .addSharedElement(transitionView, ViewCompat.getTransitionName(transitionView))
                .replace(R.id.fragment_container, categoryDetailChildFragment)
                .addToBackStack(TAG)
                .commit();

Why there is no shared transition when getChildFragmentManager()? Please help anybody.

like image 370
Wakil Ahmad Avatar asked Oct 29 '17 21:10

Wakil Ahmad


1 Answers

Every fragment has their own childFragmentManager. Therefore if you have multiple nested fragments one inside another you should refer to the same fragment's childFragmentManager, the same in which you use addSharedElement().

Therefore if you have:

ActivityA
|_ FragmentB
   |_ FragmentC
      |_ FragmentD

You should use the uppest common fragment's getChildFragmentManager() -Fragment B in this case, for Fragment C and Fragment D- to ensure every nested fragment refers to the same fragmentManager. That's why it works when you use activity's fragmentManager, because there are just one activity and every one refers to the same one by using getActivity()

To get parent's Fragment in a nested fragment you could use getParentFragment() on your nested fragment's onAttach() method. You could also cast it to a certain class like FragmentB:

override fun onAttach(context: Context) {
    super.onAttach(context)

    val fragment: FragmentB = parentFragment.parentFragment.parentFragment... as FragmentB
}
like image 81
Rubén Viguera Avatar answered Nov 03 '22 01:11

Rubén Viguera