I actually encountered same issue like OP on Android 10+ (11 dev preview also suffers from it). I spent like 2 weeks on it so I'll try to summarize my findings and a hack how I managed to fix it in my project.
So I found out that if call the code that ppxpp posted as an answer it does help when when the screen rotates (or any other config change).
Then I found out it's better to save all the shared element names into a String array in onSaveInstanceState()
like this:
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
sharedElementList?.run {
outState.putStringArrayList(PENDING_EXIT_SHARED_ELEMENTS, ArrayList(this))
}
}
}
where const val PENDING_EXIT_SHARED_ELEMENTS = "android:pendingExitSharedElements"
It's a constant defined in ActivityTransitionState
And to get the sharedElementList
you can call this in onCreate()
setEnterSharedElementCallback(object : SharedElementCallback() {
override fun onSharedElementsArrived(sharedElementNames: MutableList<String>?, sharedElements: MutableList<View>?, listener: OnSharedElementsReadyListener?) {
super.onSharedElementsArrived(sharedElementNames, sharedElements, listener)
sharedElementList = sharedElementNames?.toList()
}
}
Next up the activity actually needs to be recreated for this to have effect - so only adding this will make it work if you rotate screen on Activity B.
Therefore I call recreate()
on Activity B like 500-1000ms after I open the Activity C. That way the transition isn't laggy.
Just be cautious about calling supportPostponeEnterTransition()
and startPostponedEnterTransition()
because if they are calling them when entering Activity B, they will be called again after recreate()
In general it's enough to call the recreate once so I'm myself keeping a local flag in the Activity B for me to know if the Activity was already recreated or not yet, so that I don't do it unnecessarily too much every time I go from B to C and back.
Overall this is just a high level hacky solution and I was dealing with many more issues having recyclerviews in each Activity which makes things more complicated.
If you find any better please comment, I'd love to hear it but I can't spend any more time on this as two weeks of investigation of Android source code and comparing API28 and 29 has been enough for me :D