That Shared Element Transition…

That Shared Element Transition…

In this blog post I talked about an issue that I was having regarding the shared element transition for a project I was completing as part of my Android Developer Nanodegree. Around the time I was having this issue I wrote a short post for some close friends explaining my woes so I thought I would retell some of the story here.

So the app I was making used a thing called a recycler view. This lets you have a potentially infinite list without causing memory issues as it recycles views that are off screen to make the ones that are coming on screen when you scroll (probably a painfully simplistic way to describe it, but you get the point).

I was having an issue where if you scrolled to the bottom of the screen the shared element transitions would just stop working. Even if you scrolled back up they would just not work any more, unless you refreshed the data or restarted the app (below is a video of a working version of this transition so you know what it should look like).

I had been working on this issue for an entire day before finally discovering the reason and eventually fixing it.

To make a shared element transition you have to give the image in the list a transition name and then the matching image in the details view the same transition name (so that they are linked).

Shared element transition names

This was done on run time as the images in the list are generated from a database so you can’t be sure how many results you will get.

To make the transition name unique I would use the transition name that was set in the layout files (hardcoded to “transition photo“) and then concatenate the id of the individual image (which would be unique). The code would look like this:

String transitionName = holder.thumbnailView.getTransitionName() + id;

So lets say the ID was 5, we know the original transition name is “transition photo“. So the above  basically translates to:

transitionName = "transition photo5"

The issue is I’m using a recycler view, which likes to recycle… so when I would scroll down it would recycle an old view, and then I would call getTransitionName(), which would return “transition photo5“, but it’s still trying to make it unique so it adds on the new id (e.g 6) so it would set the transition name to “transition photo56“.

So when that item is selected in the list view the code would generate the transition name for the detail activity using the logic of “I want to join “transition photo” with the ID, which is 6“. It would then go “hey, ‘transition photo56’ doesn’t equal ‘transition photo6’ … so there’s nothing to transition“.

My problem was I was using the default transition name to build the current transition name but then overwriting the default transition name with the current transition name.

What a numpty.

A box of numpty

Leave a Reply

Your email address will not be published. Required fields are marked *