Skip to main content

Working with Animation

1. Using View Animations

Property Description Values
android:animation Specifies the animation resource to use @anim/animation_name
android:duration Duration of the animation in milliseconds 1000
android:interpolator Interpolator to control animation speed @android:anim/linear_interpolator
android:fillAfter Whether the animation should remain in final state true or false
android:startOffset Delay before animation starts in milliseconds 500

Example: Applying a Fade Animation

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/image"
    android:animation="@anim/fade_in" />

Example: Creating a Scale Animation

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/image"
    android:scaleX="0.5"
    android:scaleY="0.5"
    android:duration="1000"
    android:interpolator="@android:anim/linear_interpolator" />
Note: View animations are applied to the view's visual properties and do not affect the actual layout or position of the view.

2. Creating Animation Resources

Example: Define a fade-in animation

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:fromAlpha="0.0"
    android:toAlpha="1.0" />
Attribute Description Values
android:duration Duration of the animation in milliseconds integer
android:fromAlpha Starting opacity value (0.0 = transparent, 1.0 = opaque) float
android:toAlpha Ending opacity value float
android:interpolator Timing function for the animation @android:anim/linear, @android:anim/accelerate_decelerate_interpolator
Note: Animation resources are defined in res/anim/ directory.

Example: Define a scale animation

<?xml version="1.0" encoding="utf-8"?>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500"
    android:pivotX="50%"
    android:pivotY="50%"
    android:fromXScale="1.0"
    android:toXScale="1.5"
    android:fromYScale="1.0"
    android:toYScale="1.5" />
Attribute Description Values
android:pivotX X coordinate of the pivot point for scaling float or %
android:pivotY Y coordinate of the pivot point for scaling float or %
android:fromXScale Starting scale factor on X axis float
android:toXScale Ending scale factor on X axis float
android:fromYScale Starting scale factor on Y axis float
android:toYScale Ending scale factor on Y axis float

Example: Define a translate animation

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:fromXDelta="0%"
    android:toXDelta="100%"
    android:fromYDelta="0%"
    android:toYDelta="0%" />
Attribute Description Values
android:fromXDelta Starting X offset as a percentage or pixels float or %
android:toXDelta Ending X offset as a percentage or pixels float or %
android:fromYDelta Starting Y offset as a percentage or pixels float or %
android:toYDelta Ending Y offset as a percentage or pixels float or %

3. Starting Animations

Method Description Parameters Notes
animate() Starts an animation on a view duration: Long, interpolator: Interpolator Chainable with other animation methods
startAnimation() Starts an animation using an Animation object animation: Animation Legacy API; prefer ViewPropertyAnimator

Example: Basic Animation

val view = findViewById<View>(R.id.my_view)
view.animate()
    .translationX(100f)
    .setDuration(500)
    .start()

Example: Using Interpolator

val view = findViewById<View>(R.id.my_view)
val interpolator = AccelerateDecelerateInterpolator()
view.animate()
    .alpha(0.5f)
    .setInterpolator(interpolator)
    .setDuration(1000)
    .start()
Note: animate() returns a ViewPropertyAnimator instance, which allows chaining multiple animation properties.

4. Using Property Animations

Property Description Values Notes
animator Object that controls the animation ValueAnimator, ObjectAnimator Used to animate properties over time
duration Duration of the animation in milliseconds Long Default is 300ms
interpolator Defines the animation's timing curve TimeInterpolator Examples: LinearInterpolator, AccelerateDecelerateInterpolator

Example: Basic Property Animation

val animator = ValueAnimator.ofFloat(0f, 1f)
animator.duration = 1000
animator.addUpdateListener { animation ->
    val value = animation.animatedValue as Float
    view.alpha = value
}
animator.start()

Example: ObjectAnimator for View Properties

val animator = ObjectAnimator.ofFloat(view, "translationX", 0f, 200f)
animator.duration = 500
animator.start()
Note: Property animations are more efficient than view animations because they update the actual properties of the view.

5. Animating Multiple Properties

Property Description Values Notes
alpha Controls the transparency of a view 0.0f to 1.0f 0.0f = fully transparent, 1.0f = fully opaque
translationX Translates the view horizontally Float Positive values move right, negative left
translationY Translates the view vertically Float Positive values move down, negative up
scaleX Scales the view horizontally Float 1.0f = original size, < 1.0f = smaller, > 1.0f = larger
scaleY Scales the view vertically Float 1.0f = original size, < 1.0f = smaller, > 1.0f = larger
rotation Rotates the view around its center Float 0° = no rotation, positive values rotate clockwise
rotationX Rotates the view around its X-axis Float 0° = no rotation, positive values rotate toward the viewer
rotationY Rotates the view around its Y-axis Float 0° = no rotation, positive values rotate toward the viewer

Example: Animating Multiple Properties

val animator = ObjectAnimator.ofPropertyValuesHolder(
    view,
    PropertyValuesHolder.ofFloat("alpha", 0f, 1f),
    PropertyValuesHolder.ofFloat("translationX", -100f, 0f),
    PropertyValuesHolder.ofFloat("scaleX", 0.5f, 1f)
)

animator.duration = 1000
animator.start()
Note: Use PropertyValuesHolder to animate multiple properties in a single animator.

6. Implementing Transitions

Example: Basic Transition

val transition = TransitionDrawable(
    arrayOf(
        ContextCompat.getDrawable(this, R.drawable.image1),
        ContextCompat.getDrawable(this, R.drawable.image2)
    )
)

transition.startTransition(500) // 500ms transition
Property Description Values
startTransition(int durationMillis) Starts the transition 500 (ms)
reverseTransition(int durationMillis) Reverses the transition 300 (ms)
isRunning Checks if transition is active true / false
Note: TransitionDrawable requires at least two drawables to function.

Example: Crossfade Transition

val crossfade = ViewPropertyAnimator
    .animate(view)
    .alpha(0f)
    .setDuration(1000)
    .withEndAction {
        view.alpha = 1f
    }

Transition Types

  • Crossfade: Fades between two views
  • Slide: Slides views in/out of screen
  • Fade: Fades views in/out of screen
  • ChangeBounds: Animates size and position changes

7. Using Motion Layout

MotionLayout is a powerful layout manager in Android that enables developers to create complex animations and transitions between different layouts. It is part of the androidx.constraintlayout.widget package and provides a declarative way to define animations using XML.

Property Values Description
app:layoutDescription @xml/motion_scene Specifies the XML file containing the motion scene definition.
app:applyMotionScene true / false Indicates whether to apply the motion scene to the layout.
app:progress 0.0 to 1.0 Controls the progress of the animation, where 0.0 is start and 1.0 is end.

Example: Basic Motion Layout Setup

<androidx.constraintlayout.motion.widget.MotionLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutDescription="@xml/motion_scene">

    <View
        android:id="@+id/box"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:background="@color/colorPrimary" />

</androidx.constraintlayout.motion.widget.MotionLayout>

Example: Motion Scene Definition

<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Transition
        app:constraintSetEnd="@+id/end"
        app:constraintSetStart="@+id/start">

        <KeyFrame>
            <KeyPosition
                app:target="@+id/box"
                app:percentX="0.5"
                app:percentY="0.5" />
        </KeyFrame>

    </Transition>

    <ConstraintSet android:id="@+id/start">
        <Constraint
            android:id="@+id/box"
            android:layout_width="64dp"
            android:layout_height="64dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint
            android:id="@+id/box"
            android:layout_width="64dp"
            android:layout_height="64dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent" />
    </ConstraintSet>

</MotionScene>
Note: MotionLayout is ideal for creating complex UI transitions and animations that involve multiple views changing their positions, sizes, or other properties over time.

8. Creating Circular Reveal

Property Description Values
revealRadius Radius of the circular reveal float
centerX X coordinate of the center point float
centerY Y coordinate of the center point float

Example: Circular Reveal Animation

val revealAnimator = ViewAnimationUtils.createCircularReveal(
    view,
    centerX,
    centerY,
    0f,
    maxRadius
)

revealAnimator.duration = 500
revealAnimator.start()
Note: The createCircularReveal method is available from API level 21 (Android 5.0).
Warning: Ensure the view is visible before starting the animation to avoid visual glitches.

9. Interpolating Animations

Property Description Values
interpolator Defines the rate of change of an animation LinearInterpolator, AccelerateInterpolator, DecelerateInterpolator, AccelerateDecelerateInterpolator
animationTime Duration of the animation in milliseconds 1000, 2000

Example: Using Interpolator

val animation = TranslateAnimation(0f, 100f, 0f, 0f)
animation.duration = 1000
animation.interpolator = AccelerateInterpolator()
Note: Interpolators control the pacing of animations. Common interpolators include LinearInterpolator, AccelerateInterpolator, and DecelerateInterpolator.

10. Handling Animation Lifecycle

Method Description Notes
onAnimationStart() Called when the animation begins. Use to initialize state or trigger side effects.
onAnimationEnd() Called when the animation completes. Use to clean up or trigger next actions.
onAnimationRepeat() Called when the animation repeats (if set to repeat). Use for continuous effects or resetting state.

Example: Using Animation Listeners

val animator = ValueAnimator.ofFloat(0f, 1f)
animator.addUpdateListener { animation ->
    val value = animation.animatedValue as Float
    // Update view properties here
}
animator.addListener(object : AnimatorListenerAdapter() {
    override fun onAnimationStart(animation: Animator) {
        // Animation started
    }

    override fun onAnimationEnd(animation: Animator) {
        // Animation finished
    }
})
Note: AnimatorListenerAdapter is a convenience class that provides default no-op implementations for all listener methods, allowing you to override only the ones you need.

11. Using Animated Vector Drawables

Animated vector drawables allow you to animate vector graphics defined in XML. They are useful for creating smooth, scalable animations without raster images.

Property Description Values
android:name Name of the animated vector drawable resource anim_vector_drawable
android:drawable Reference to the vector drawable resource @drawable/vector_drawable

Example: Defining an Animated Vector Drawable

<animated-vector xmlns:android="http://schemas.android.com/apk/res/android">
    <target
        android:name="vector_path"
        android:drawable="@drawable/vector_drawable" />
    <animation
        android:duration="1000"
        android:interpolator="@android:anim/linear_interpolator" />
</animated-vector>

Example: Using Animated Vector Drawable in Layout

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/animated_vector_drawable" />
Note: Animated vector drawables are supported on API level 21 and above.
Warning: Complex animations may impact performance on older devices.

Was this article helpful?