I got images adapter where each item is user image, when clicked it opens a new activity with selected user image, so I mark the image as shared element and using activity transitions.
Part of the actions that I perform on the second activity effects all of the users, so the adapter calls notifyDataSetChanged
and reset the position to the top of the list.
When this happens it mess up the return animation, when I close the second activity and return to the list the data in it been changed so the image get animated to the wrong cell.
I got two questions:
- What can I do to remap the animation to the right cell? All the cells got the same shared id...
- In case that my user is no longer visible on the list, how can I replace the return animation with different animation?
In the first activity you should have some key that specifies the item that launches second activity. Let's assume you have a
Map
of uniqueuserId
s andUser
s, i.e.Map<Integer, User>
.User
's key in the map, let's say it is42
. (In the map42 -> John Doe
, and you are launching second activity forJohn Doe
).setExitSharedElementCallback()
in the first activity and overrideonMapSharedElements()
.Override
onActivityReenter()
in first activity and postpone transition withsupportPostponeEnterTransition()
, in order not to show transition until we've made some actions (e.g. we want to scroll the list in order to show the item).onActivityReenter()
save theBundle
that you've passed from second activity viaIntent
(we'll see in step 7).onActivityReenter()
perform some changes to the UI based on the information you've added to this bundle. Particularly, in our case this bundle will include the originalInteger
key of theUser
that launched second activity. You may find current place of theUser
in the list by this key, and scrollRecyclerView
to that new position. After making this item visible you can push the trigger and let the system start the transition bysupportStartPostponedEnterTransition()
.In
SharedElementCallback::onMapSharedElements()
check weather theBundle
that you have saved in the step 4 is null or not. If it is not null, that would mean that you have made something in second activity and you want remapping of shared elements to happen. This means you have to do something like this:In second activity override
finishAfterTransition()
:You can either make it visible (e.g. by scrolling
RecyclerView
so much, that your view becomes visible), or you can just remove shared elements transition in step 6 by clearing outnames
andsharedElements
and not adding anything into them.I hope you've learned the concept how it works although it seems a bit messy. But as a help for you I can share some code from an app written by me:
MainActivity - MainPresenter
DetailActivity