Android Transition Framework: Getting Started
In this tutorial, you’ll learn how to animate your UI with Android Transition Framework. By Zahidur Rahman Faisal.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Android Transition Framework: Getting Started
15 mins
- Switching Activities with Shared Elements
- Tracking Animation States with Lifecycle Callbacks
- Animating Transitions Between Fragments
- Creating the Image Viewer
- Sharing Transition Elements Between Fragments
- Scene Transitions
- Creating Scenes
- Switching Scenes
- Creating Custom Transitions
- Applying Custom Transitions
- Where To Go From Here?
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:
Getting Started
Creating a Transition
Click the Download Materials button at the top or bottom of this tutorial. Unzip the iSellTransition.zip folder.
Now, launch Android Studio 3.3.1 or greater and select Open an existing Android Studio project to import the starter project.
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:
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.
First, modify the default Activity Transition Animation by adding a single line of code inside SplashActivity, right before calling finish()
:
- 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.
- data: Model/data classes.
- ui: User interfaces related to classes.
- util: Common utility classes shared throughout the app.
- data: Model/data classes.
- ui: User interfaces related to classes.
- util: Common utility classes shared throughout the app.
- data: Model/data classes.
- ui: User interfaces related to classes.
- util: Common utility classes shared throughout the app.
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:
Open content_details.xml and insert into priceTextView
:
- Update
onItemClick()
from ListActivity.kt:override fun onItemClick(item: Item, itemView: View) { val detailsIntent = Intent(this, DetailsActivity::class.java) detailsIntent.putExtra(getString(R.string.bundle_extra_item), item) // 1 - Start Activity with shared-transition animation val activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation( this@ListActivity, Pair.create<View, String>( //2 itemView.findViewById(R.id.itemImageView), // 3 getString(R.string.transition_image)), Pair.create<View, String>( itemView.findViewById(R.id.itemPrice), getString(R.string.transition_price))) startActivity(detailsIntent, activityOptions.toBundle()) }
- Open fragment_details.xml from the res ▸ layout package and add a transition name to
itemImageView
:android:transitionName="@string/transition_image"
android:transitionName="@string/transition_price"
override fun onItemClick(item: Item, itemView: View) {
val detailsIntent = Intent(this, DetailsActivity::class.java)
detailsIntent.putExtra(getString(R.string.bundle_extra_item), item)
// 1 - Start Activity with shared-transition animation
val activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(
this@ListActivity,
Pair.create<View, String>( //2
itemView.findViewById(R.id.itemImageView), // 3
getString(R.string.transition_image)),
Pair.create<View, String>(
itemView.findViewById(R.id.itemPrice),
getString(R.string.transition_price)))
startActivity(detailsIntent, activityOptions.toBundle())
}
android:transitionName="@string/transition_image"
android:transitionName="@string/transition_price"
Ready for magic? The output is awesome! Build and run again.
So smooth! Time to break it down:
- Use
ActivityOptionsCompat.makeSceneTransitionAnimation()
to specify the view and transition name as aPair
passed asBundle
from ListActivity to DetailsActivity. - Share multiple
Pair
s of View and String as arguments to that function. This is equivalent to sharingitemImageView
anditemPrice
views along with their transition names. - Specify
itemImageView
from fragment_details.xml as a final view for transition animation. Repeat the same steps forpriceTextView
in content_details.xml.
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) {
shareFab.show()
}
With:
activity?.window?.sharedElementEnterTransition?.addListener(
object : Transition.TransitionListener {
override fun onTransitionStart(transition: Transition) {}
override fun onTransitionEnd(transition: Transition) {
shareFab?.let {
if (!shareFab.isShown) {
shareFab.show()
}
}
}
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="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/details_scene_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.details.GalleryFragment">
<ImageView
android:id="@+id/itemImageView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scaleType="fitCenter"
android:transitionName="@string/transition_image" />
<TextView
android:id="@+id/titleTextView"
style="@style/TextAppearance.AppCompat.Headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/default_padding"
android:layout_marginTop="@dimen/default_padding"
android:gravity="center"
android:text="@string/hint_title" />
</LinearLayout>
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.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.raywenderlich.isell.R
import com.raywenderlich.isell.data.Item
import kotlinx.android.synthetic.main.fragment_gallery.*
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 {
populateDetails(item)
}
}
// 3
private fun populateDetails(item: Item?) {
itemImageView.setImageResource(item?.imageId!!)
titleTextView.text = item.title
}
}
Here’s what the code above does:
- Generate the view for this Fragment from fragment_gallery.xml.
- Retrieve
item
from DetailsActivity. CallspopulateDetails()
to populate data when the view is ready. - Assign item’s image and title to
itemImageView
andtitleTextView
.