Android Transition Framework: Getting Started

In this tutorial, you’ll learn how to animate your UI with Android Transition Framework. By Zahidur Rahman Faisal.

Leave a rating/review
Download materials
Save for later

Think about the last Android app you used. What aspect impressed you the most? Was it the user experience? All users appreciate an app that’s easy to use and blazing fast with cool animations.

With Google’s Android Transition Framework, you can add style, elegance and screen transitions to user interactions.

Android Transition Framework allows you to:

  • Animate automatically from starting view to ending view by providing the layouts.
  • Use predefined common animations such as Translate, Resize and Fade.
  • Load built-in animations from layout resource files.
  • Apply one or many animation effects to a view group at once.
  • Use scenes loaded from complex layouts or generated programmatically.
  • Control an animation’s lifecycle and progress providing the callbacks.
  • Create custom transition animations.
    • Getting Started

      Click the Download Materials button at the top or bottom of this tutorial. Unzip the folder.

      Now, launch Android Studio 3.3.1 or greater and select Open an existing Android Studio project to import the starter project.

      Android Studio 3.3.1

      Choose iSellTransition-Starter inside the iSellTransition folder and click Open.

      The iSellTransition-Starter project contains the necessary classes and utilities to make an e-commerce app. It has three main packages:

      • data: Model/data classes.
      • ui: User interfaces related to classes.
      • util: Common utility classes shared throughout the app.
        • Note: Kotlin Android Extensions are used for View Binding in this project. Views are referenced directly using their id instead of findViewById() throughout the project.

          Android Transition Framework offers many ways to create beautiful animations or override default ones. In the next section, you’ll create a transition and animate transitions between activities. Unleash that power now.

          Creating a Transition

          First, modify the default Activity Transition Animation by adding a single line of code inside SplashActivity, right before calling finish():

overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right)

Build and run the project.

Adding this line overrides the default enter and exit animations by referencing the existing slide-in and slide-out animations in the Android library. Easy!

Switching Activities with Shared Elements

One the most popular features of Android Transition Framework is sharing elements such as image and texts between activities during transitions.

Implement this complex animation with two simple steps:

  1. Update onItemClick() from ListActivity.kt:
    override fun onItemClick(item: Item, itemView: View) {
      val detailsIntent = Intent(this,
      detailsIntent.putExtra(getString(R.string.bundle_extra_item), item)
      // 1 - Start Activity with shared-transition animation
      val activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
        Pair.create<View, String>(                   //2
          itemView.findViewById(, // 3
        Pair.create<View, String>(
      startActivity(detailsIntent, activityOptions.toBundle())
  2. Open fragment_details.xml from the res ▸ layout package and add a transition name to itemImageView:

    Open content_details.xml and insert into priceTextView:

Note: Add the transition name for shared views in the strings.xml file. Use the same string among layouts to be consistent and avoid typos.

Ready for magic? The output is awesome! Build and run again.

So smooth! Time to break it down:

  1. UseActivityOptionsCompat.makeSceneTransitionAnimation() to specify the view and transition name as a Pair passed as Bundle from ListActivity to DetailsActivity.
  2. Share multiple Pairs of View and String as arguments to that function. This is equivalent to sharing itemImageView and itemPrice views along with their transition names.
  3. Specify itemImageView from fragment_details.xml as a final view for transition animation. Repeat the same steps for priceTextView in content_details.xml.
Note: priceTextView has a different id from the starting view itemPrice. Don’t worry, the transition works as long as both have the same transition name and same view type, TextView.

Tracking Animation States with Lifecycle Callbacks

Now that you’ve implemented the shared element transition, you may also want to set up notification when it’s started and finished. Android Transition Framework provides a flexible API to track different animation states.

There’s a floating Share button over the product image in DetailsFragment. The button overlaps with the image transition animation. What if you could make the button visible right after the transition animation ends?

To do that, add a listener to the shared transition animation, replacing the following code at line 65 inside DetailsFragment.kt:

if (!shareFab.isShown) {


  object : Transition.TransitionListener {

  override fun onTransitionStart(transition: Transition) {}

  override fun onTransitionEnd(transition: Transition) {
    shareFab?.let {
      if (!shareFab.isShown) {

  override fun onTransitionCancel(transition: Transition) {}

  override fun onTransitionPause(transition: Transition) {}

  override fun onTransitionResume(transition: Transition) {}

The code above adds a TransitionListener interface to the active window’s sharedElementEnterTransition property, which holds the transition states.

TransitionListener allows you to track when the transition starts, ends, cancels, pauses or resumes. You make shareFab button visible on the onTransitionEnd() callback.

Build and run again.

Now the share button appears right after the shared transition animation.

Animating Transitions Between Fragments

Animating and sharing elements can get tricky during fragment-to-fragment transitions, but don’t worry. You can learn the trick!

Create a new Fragment called GalleryFragment, showing a complete image of the items displayed in DetailsFragment.

Creating the Image Viewer

Create fragment_gallery.xml inside the layout package. Add the code below inside the file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

    android:transitionName="@string/transition_image" />

    android:text="@string/hint_title" />

That’s a LinearLayout to display the image and title of the selected item.

Note that you added android:transitionName="@string/transition_image" to define a transition name for the shared element.

Now, create GalleryFragment.kt class inside the details package. Then, replace the class code with:

package com.raywenderlich.isell.ui.details

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import com.raywenderlich.isell.R

class GalleryFragment : Fragment() {

  private var item: Item? = null

  // 1
  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                            savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_gallery, container, false)

  // 2
  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    item = activity?.intent?.getParcelableExtra(getString(R.string.bundle_extra_item))
    item?.let {

  // 3
  private fun populateDetails(item: Item?) {
    titleTextView.text = item.title

Here’s what the code above does:

  1. Generate the view for this Fragment from fragment_gallery.xml.
  2. Retrieve item from DetailsActivity. Calls populateDetails() to populate data when the view is ready.
  3. Assign item’s image and title to itemImageView and titleTextView.

Sharing Transition Elements Between Fragments

It’s time for a transition.

Open DetailsFragment again. Inside onViewCreated(), after transition animation callbacks, add a click listener to itemImageView. This will open the GalleryFragment when a user taps on it.

Add this code:

itemImageView.setOnClickListener {
  val changeImageAnimation = ChangeImageTransform()
  val galleryFragment = GalleryFragment()
  galleryFragment.sharedElementEnterTransition = changeImageAnimation
  galleryFragment.sharedElementReturnTransition = changeImageAnimation

      .addSharedElement(itemImageView, itemImageView.transitionName)
      .replace((view.parent as ViewGroup).id,


The code above performs four steps:

  1. Define a transition animation. changeImageAnimation is an instance of a library class from Android Transition Framework, which animates the shared image’s bounds from starting scene to ending scene.
  2. Create a GalleryFragment instance and assigns changeImageAnimation as enter and return shared transition animation.
  3. Navigate to GalleryFragment.
  4. Attach itemImageView as a shared element, followed by the transition name defined in the layout xml.
Note: Play around with other predefined transitions from that library such as Fade and Slide.

Build and run again.

Tap the image from detail screen to see the image animate, and bask in its glory:

Scene Transitions

Android Transition Framework provides an awesome feature called Scene Transition to switch views or layouts on the go.

You can create a Scene from a layout resource file or from a view or view group programmatically. Start by creating a scene from layouts.

Creating Scenes

Create scene_item_image.xml inside layout package and add the code below:

<?xml version="1.0" encoding="utf-8"?>
<ImageButton xmlns:android=""
  android:scaleType="fitCenter" />

Then create another file named scene_upload.xml in the same package with the following layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""

    android:layout_centerInParent="true" />

    android:textColor="@color/colorAccent" />


Now, replace ImageButton inside activity_add_item.xml with FrameLayout :

  <include layout="@layout/scene_item_image" />

In the same em>activity_add_item.xml, find the TextView with id categoryTitle, and replace the property android:layout_below="@+id/imageButton" with android:layout_below="@+id/sceneContainer".

Similarly, find the Spinner with id categorySpinner and replace the property android:layout_below="@+id/imageButton" with android:layout_below="@+id/sceneContainer"

In the above steps, you created two separate layouts (scene_item_image.xml and scene_upload.xml) and are showing one of them (scene_item_image.xml) in activity_add_item.xml. In the next section, you’ll add a listener when clicking the Add Item button inside AddItemActivity, which will trigger a scene transition from scene_item_image.xml to scene_upload.xml.

Switching Scenes

Now, open AddItemActivity and add the lines below to the import section on top:


The starting scene for your transition is automatically determined from the current layout. You need to provide a target scene for your TransitionManager to switch scenes.

To satisfy that, add the following code inside onClickAddItem() within if (hasValidInput()) { ... }:

fun onClickAddItem(view: View) {
  if (hasValidInput()) {
    // 1 - Apply Scene transition for uploading
    val uploadScene: Scene = Scene.getSceneForLayout(sceneContainer, R.layout.scene_upload, this)
    // 2
    TransitionManager.go(uploadScene, Fade())
     // ...

The code above does two things:

  1. Execute Scene.getSceneForLayout() to generate the scene and assign it to uploadScene. In order to generate a Scene, you need three parameters:
    1. A reference to the scene root, which is sceneContainer.
    2. A layout resource id, which is R.layout.scene_upload.
    3. A reference to the current context.
  2. Call TransitionManager.go() providing uploadScene and a Fade animation to override the default transition.

Build and run to see the changes.

Navigate to add a new item. Click Add Item to see the Scene Transition in action:

Congrats, and nice work! You’ll learn to animate the uploading process in the next part of this tutorial.

Creating Custom Transitions

You can create you own transition animation, simulating an upload process in AddItemActivity.

To create a transition, you need to extend Transition class from Android Transition Framework and manipulate your animation.

To do that, you’ll customize the default progress animation of ProgressBar.

Create a new class named ProgressBarTransition inside the util package and add following code:

package com.raywenderlich.isell.util

import android.widget.ProgressBar
import android.view.ViewGroup
import android.animation.Animator
import android.animation.ObjectAnimator
import android.view.animation.DecelerateInterpolator

class ProgressBarTransition : Transition() {

  val PROGRESSBAR_PROPERTY = "progress"
  val TRANSITION_PROPERTY = "ProgressBarTransition:progress"

  // 1
  override fun createAnimator(sceneRoot: ViewGroup, startValues: TransitionValues?,
                              endValues: TransitionValues?): Animator? {
    if (startValues != null && endValues != null && endValues.view is ProgressBar) {
      val progressBar = endValues.view as ProgressBar
      val startValue = startValues.values[TRANSITION_PROPERTY] as Int
      val endValue = endValues.values[TRANSITION_PROPERTY] as Int
      if (startValue != endValue) {
        // 2
        val objectAnimator = ObjectAnimator
                .ofInt(progressBar, PROGRESSBAR_PROPERTY, startValue, endValue)
        objectAnimator.interpolator = DecelerateInterpolator()

        return objectAnimator

    return null
  // 3
  private fun captureValues(transitionValues: TransitionValues) {
    if (transitionValues.view is ProgressBar) {
      // Save current progress in the transitionValues Map
      val progressBar = transitionValues.view as ProgressBar
      transitionValues.values[TRANSITION_PROPERTY] = progressBar.progress

  // 4
  override fun captureStartValues(transitionValues: TransitionValues) {

  // 5
  override fun captureEndValues(transitionValues: TransitionValues) {


In the first part of the code above, the important arguments are startValues and endValues as TransitionValues. A TransitionValues instance holds information about the View and a Map with properties and current values from the view.

The arguments startValues and endValues contain the value for a property name modified in this transition. If there are startValues and endValues and the view type is ProgressBar, then the code extracts the values and puts them into startValue and endValue variables, respectively.

Here’s what the remaining code does:

  1. Creates an ObjectAnimator to animate changes of the progress property from ProgressBar. Set a DecelerateInterpolator to reflect the hustle of uploading data during the progress animation.
  2. Takes the progress value of the progress bar and save it to TransitionValues instance internal Map along with TRANSITION_PROPERTY.
  3. Stores the starting state using captureStartValues().
  4. Stores the end state of the transition using captureEndValues().

Applying Custom Transitions

Now, you’ll apply your custom transition while simulating the upload process. Open AddItemActivity and import ProgressBarTransition:

import com.raywenderlich.isell.util.ProgressBarTransition

Then, replace everything inside onClickAddItem():

fun onClickAddItem(view: View) {
  if (hasValidInput()) {
    // Scene Transition
    val uploadScene: Scene = Scene
            .getSceneForLayout(sceneContainer, R.layout.scene_upload, this)
    TransitionManager.go(uploadScene, Fade())

    // 1
    val uploadTime: Long = 3000
    val statusInterval: Long = 600

    object : CountDownTimer(uploadTime, statusInterval) {
      val maxProgress = 100
      var uploadProgress = 0

      // 2
      override fun onTick(millisUntilFinished: Long) {
        if (uploadProgress < maxProgress) {
          uploadProgress += 20
              .beginDelayedTransition(sceneContainer, ProgressBarTransition())
          progressBar.progress = uploadProgress

      // 3
      override fun onFinish() {
        uploadStatus.text = getString(R.string.text_uploaded)

Here’s what’s happening in the code above:

  1. Declare uploadTime for three seconds and statusInterval for 600 milliseconds. CountDownTimer will fire its onTick() function five times before going to onFinish().
  2. onTick() checks whether uploadProgress reached 100%. If not, it increases uploadProgress by 20% and calls TransitionManager.beginDelayedTransition() to apply your custom ProgressBarTransition on sceneContainer.
  3. onFinish() fires after three seconds. Change uploadStatus text to Upload complete! and then add a confirmation message by calling addItemData() and showAddItemConfirmation().

Build and run now, and try adding another item:

Congratulations! You've mastered the art of transitions and turned a simple app into an awesome one!

Where To Go From Here?

Get the final project by clicking the Download Materials button at the top or bottom of this tutorial.

Keep your users excited with the magic of Android animations. Here are some additional resources to explore:

I hope learning Android Transition Framework helps you create amazing user experiences for your next app. If you have questions or comments, please join the forum discussion and comment below!