I'm having a problem with memory leak in EnterTransitionCoordinator
while using shared element transitions. Below you can see the app structure:
It has 2 screens, first is an Activity
with DrawerLayout
and few Fragment
s inside. One of them consists a list of photos and clicking specific photo triggers shared element transition to Fragment
from ViewPager
located in another Activity
. I'm using custom SharedElementCallback
when exiting and reentering these two Activity
s for mapping a correct View
for shared element transition. I based my code on this great blog post: https://android.jlelse.eu/dynamic-shared-element-transition-23428f62a2af
The problem is, that after swiping between ViewPager
's items, Fragment
s are being destroyed, but the View
used for shared element transition is being kept in Activity
's ActivityTransitionState
, specifically in EnterTransitionCoordinator
. The same when reentering to Activity
with DrawerLayout
and then opening another Fragment
. References to View
s used for shared element transitions are still kept int Activity
s even though Fragment
s were destroyed, which causes a memory leak.
My question: Is there a good way to avoid this memory leak?
I discovered that there's a method
clearState()
inEnterTransitionCoordinator
, which should be called inActivity.onStop()
. But since theActivity
is not yet being stopped,View
s fromFragment
s are being leaked. As a temporary workaround, I'm clearing that state manually onFragment.onDestroyView()
by calling this method with reflection. Below you can see the code: