Thursday, September 10, 2015

Fun with Transitions

Do you want to add custom transitions to fragments or any other view hierarchy change?

Me too. I want an easy way to add custom animations to any view hierarchy change. And also I want it to be easy to use. Actually I like everything to be easy to use.

Lets start with regular views. To add fancy custom animation we need to take content's snapshot before hierarchy change and in some cases after. Not all animations require snapshot of final state (for ex. look at RevealTransition.java).

Now about fragments. Essentially most of the time they represent views and it means that they can be animated same way. But there is a catch - fragment manager will change hierarchy only on next Looper pass. It means that we need to:
  • skip first frame drawn
  • or to call FragmentManager.executePendingTransactions();

This is how my implementation looks like:



Now about the code. Most of the work is done inside TransitionView. All you need to do is to pass any Transition object via TransitionView.startTransition(), make desired hierarchy change and it will do the rest.
  mTransitionView.startTransition(new RevealTransition(anchor));

  getSupportFragmentManager().beginTransaction()
      .replace(R.id.content, MainFragment.newInstance())
      .commit();
Transition itself is a very simple class that is responsible for actually drawing each frame. It also has few callbacks:
  • onStarting - called right after TransitionView.startTransition() (initial image can be taken here)
  • onStarted - called when hierarchy was changed (final image can be taken here)
  • onEnding - called before last animation frame
  • onEnded - called after last animation frame was drawn

It also has Transition.draw() method that is responsible for actual animation drawing.

Have fun! :)

https://github.com/MatrixDev/FunWithTransitions