Kahibaro
Discord Login Register

25.1 View Animations

Understanding View Animations in Android

View animations provide a simple way to add motion to existing views by changing how they are drawn over time. They do not change the actual layout position or size in the view hierarchy, but they visually transform views for the user. This chapter focuses on the classic view animation system, sometimes called tween animation, that you can use with any standard view.

What View Animations Can Do

View animations can modify how a view appears on the screen over a specified time interval. The common transformations are fading, moving, scaling, and rotating. These changes are applied visually, so the underlying layout position and size of the view stay the same from the system point of view.

This is important to understand. If you animate a button from the left side of the screen to the right, touch events still consider the button to be at its original position during a traditional view animation. View animations are mainly for visual effects, not for changing interaction logic.

Types of View Animations

Classic view animations support four basic transformation types. You will see them both in code and XML.

The first type is alpha animation. This changes the transparency of a view, for example fading it in from completely invisible to fully visible. It manipulates the alpha value of the view between 0 and 1.

The second type is translate animation. This moves the rendering of a view from one position to another. The view is drawn as if it moves on the screen, but its layout coordinates do not change. You can move a view horizontally, vertically, or both.

The third type is scale animation. This changes the size at which the view is drawn. You can make a view grow or shrink, in the horizontal direction, vertical direction, or both. You can also define the pivot point around which scaling happens, for example from the center of the view.

The fourth type is rotate animation. This rotates the view around a pivot point by a defined number of degrees. You can rotate clockwise or counterclockwise and set any pivot, such as the center or a corner.

Defining Animations in XML

You can define view animations in XML files placed in the res/anim directory. Each XML file describes a single animation or a set of them. The structure uses specific animation tags and attributes that the framework reads to create the animation objects for you.

To create this directory, right click the res folder in Android Studio, choose New, then Android Resource Directory, and set the resource type to anim. XML files inside this folder typically represent one animation each, for example fade_in.xml or slide_up.xml.

A simple alpha animation XML might look like this.

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:duration="500" />

The root tag alpha defines the type of animation. The fromAlpha and toAlpha attributes specify the start and end values. The duration attribute sets how long the animation runs in milliseconds.

A translate animation has a similar pattern.

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%"
    android:toXDelta="100%"
    android:fromYDelta="0%"
    android:toYDelta="0%"
    android:duration="300" />

The fromXDelta and toXDelta attributes define how far the view moves horizontally, relative to its original position. Percentage values such as 100% refer to the size of the view itself. You can also use pixel values such as 100dp or -50dp.

Scale and rotate animations use scale and rotate tags with attributes for start and end values and pivot points. The pivot point attributes, pivotX and pivotY, can also use percentage values, for example 50% to indicate the center of the view.

Combining Multiple Animations with AnimationSet

Very often you want to run several animations together or one after the other. For example, you might want a view to fade in while sliding up from the bottom. View animations support this with AnimationSet in XML or in code.

In XML, you wrap child animations inside an set tag.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator">
    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:duration="300" />
    <translate
        android:fromYDelta="50%"
        android:toYDelta="0%"
        android:duration="300" />
</set>

In this example, both the alpha and translate animations start at the same time and share a common interpolator defined on the set. You can also assign different start offsets to child animations so that one begins after another. This is done with the android:startOffset attribute in each child animation.

There is also a boolean attribute android:shareInterpolator on the set element which controls whether the child animations all use the interpolator defined in the set or their own interpolators.

Loading and Starting View Animations in Code

To use an animation defined in XML, you need to load it in your activity or fragment and then apply it to a view. The typical pattern is to use the AnimationUtils helper class.

A common usage looks like this in Kotlin.

val fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in)
myView.startAnimation(fadeIn)

The first line reads the XML animation file res/anim/fade_in.xml and creates an Animation object. The second line applies that animation to myView. Once you call startAnimation, the animation begins immediately.

You can also create animations directly in code by instantiating classes like AlphaAnimation, TranslateAnimation, ScaleAnimation, or RotateAnimation. You configure properties such as duration and start offset through methods on these objects, then call startAnimation on the view.

For example, to create a simple fade out entirely in code.

val fadeOut = AlphaAnimation(1.0f, 0.0f).apply {
    duration = 500
    fillAfter = true
}
myView.startAnimation(fadeOut)

Here, fillAfter controls what happens after the animation finishes. When it is true, the view keeps the final animated state visually. When it is false, the view snaps back to its original drawing state once the animation is done.

Duration, Delays, and Repeats

Every view animation has a duration that defines how long it takes to complete. The duration is in milliseconds, so android:duration="500" means half a second. Choosing the right duration is important. Very short animations might feel hard to notice, while very long ones can make the app feel slow.

You can delay the start of an animation with android:startOffset in XML or the startOffset property in code. This is useful for staggered animations. For example, you might make list items appear one after another, each with a small delay.

Repeating animations are supported through repetition attributes. In XML, android:repeatCount controls how many extra times the animation should play after the initial run. Use -1 to repeat indefinitely. The android:repeatMode attribute controls what happens when the animation repeats. The two common values are restart which jumps back to the start, and reverse which plays the animation backward.

In code, you use properties repeatCount and repeatMode on the animation object. The constant Animation.INFINITE represents an endless repeat. For example, a pulsing animation might repeatedly scale a view up and down with repeatMode = Animation.REVERSE.

Be careful with animations that repeat forever. Make sure they are stopped when not visible or needed, otherwise they can waste CPU and battery resources.

Interpolators and Motion Feel

The speed of an animation over time is controlled by an interpolator. The interpolator defines how the animation progresses from the start value to the end value. Without considering coordinates, it acts as a function that maps the elapsed fraction of time to the fraction of the property change.

The simplest interpolator is linear. With a linear interpolator, the property changes at a constant rate over the whole duration. However, linear motion often looks mechanical and less natural.

Android provides standard interpolators that give a more dynamic feeling. The accelerate interpolator starts slowly, then speeds up near the end. The decelerate interpolator starts fast, then slows down before stopping. The accelerate decelerate interpolator starts slowly, speeds up in the middle, then slows down again near the end.

You can reference these built in interpolators in XML using android:interpolator="@android:anim/..." on an animation or animation set. In code, you can set them using animation.interpolator = AccelerateDecelerateInterpolator() for example.

Choosing interpolators that match the expected behavior can make animations feel more natural. A sliding in view might use a decelerate interpolator so it eases into place. A disappearing element might use an accelerate interpolator so it seems to quickly get out of the way.

Listening to Animation Events

Sometimes you need to perform actions at specific points in the animation lifecycle, such as when the animation starts or ends. For that purpose, view animations provide an AnimationListener interface.

You can use it in Kotlin like this.

val slideUp = AnimationUtils.loadAnimation(this, R.anim.slide_up)
slideUp.setAnimationListener(object : Animation.AnimationListener {
    override fun onAnimationStart(animation: Animation?) {
        // Optional setup before animation starts
    }
    override fun onAnimationEnd(animation: Animation?) {
        // Actions after the animation ends
        myView.visibility = View.GONE
    }
    override fun onAnimationRepeat(animation: Animation?) {
        // Respond to a repeat cycle if needed
    }
})
myView.startAnimation(slideUp)

The onAnimationStart method is called when the animation begins. The onAnimationEnd method is triggered when the animation finishes and does not have any more repetitions. The onAnimationRepeat method is called every time the animation loops in repeat mode.

This listener is helpful when you need to change visibility at the end of a fade out, start another animation after the current one, or trigger some logic after a motion completes.

Limits and Typical Use Cases of View Animations

View animations are useful for quick visual effects applied to existing views, especially when you do not need to change their real layout properties. They are relatively simple to set up and can be defined purely in XML. This makes them suitable for basic screen transitions, making views appear or disappear smoothly, or drawing attention to a button with a small pulse effect.

However, view animations have a key limitation. They do not modify the actual properties used by the layout or hit testing. This means the system still believes the view is where it originally was. Because of that, they are not appropriate for animations where the final position should be used for interactions or where you need precise control of the animated properties in code.

When you design motion in your app, use view animations for simple one off effects on views already in place in the layout, such as fading, sliding, and basic attention grabbing motions. For more complex, property driven motion or when you need the view’s properties to reflect the visual changes, you will use other animation approaches that are introduced elsewhere.

Views: 2

Comments

Please login to add a comment.

Don't have an account? Register now!