Android SharedPreferences Tutorial and Example

Create animated transitions with MotionLayout

Creating animated transitions with MotionLayout starts with a useful rule: every visual change is movement between two constrained layouts. Instead of swapping screens and hiding the seam, you define a start state, an end state, and the rules connecting them. MotionLayout handles the interpolation, allowing the same transition to react to a swipe, a button, or code.

A compact route card works well for learning. Picture a Sydney journey planner opening a saved trip, a Melbourne café booking revealing its address and opening hours, or a Canberra events guide expanding a listing. Each example turns a small list into a detailed panel without losing the user’s sense of place.

MotionLayout belongs to AndroidX ConstraintLayout rather than the older Animator APIs. It is useful for shared elements, expanding cards, onboarding panels, and bottom-sheet-style transitions where several properties must move together. The examples use Kotlin, XML, and Material views, but the scene format also works with Java and Compose hosts.

Build the project in Android Studio, enable view binding, and use the MotionScene editor for a visual preview. Keep the first example small: one header, two text rows, one hidden details block, and one button. That gives you a clear before-and-after relationship before adding gestures or keyframes.

Prepare the Android project

Create an Empty Views Activity with a minimum SDK of 21 or later, then add the ConstraintLayout dependency to the app module. If the project already includes a compatible version, retain it unless Android Studio reports a compatibility issue.

dependencies {
    implementation("androidx.constraintlayout:constraintlayout:2.2.1")
}

Use MotionLayout as the root element of the screen layout. Assign it the ID card_scene and point layoutDescription at a MotionScene resource named card_scene.xml. XML resources and view IDs occupy separate namespaces, so the repeated name is harmless.

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

Give the child views the IDs hero, title, summary, details, and action. Constrain the header to the parent, place the title and summary below it, and position the action button below the summary. Set details to gone in the compact layout.

Model the card’s two states

The base layout represents the start state. The scene clones those constraints into @id/start, then creates @id/end by changing the header height, spacing, and hidden state. A transition between the sets defines which properties remain continuous.

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

    <Transition
        android:id="@+id/card_transition"
        motion:constraintSetStart="@id/start"
        motion:constraintSetEnd="@id/end"
        motion:duration="420" />

    <ConstraintSet
        android:id="@+id/start"
        motion:deriveConstraintsFrom="@id/card_scene" />

    <ConstraintSet
        android:id="@+id/end"
        motion:deriveConstraintsFrom="@id/start">

        <Constraint
            android:id="@id/hero"
            android:layout_height="240dp" />

        <Constraint
            android:id="@id/title"
            android:layout_marginTop="24dp" />

        <Constraint android:id="@id/details">
            <PropertySet android:visibility="visible" />
        </Constraint>

        <Constraint
            android:id="@id/action"
            android:layout_marginTop="20dp"
            motion:layout_constraintTop_toBottomOf="@id/details" />
    </ConstraintSet>
</MotionScene>

The start set derives from the base layout, while the end set changes selected properties. The header becomes 240dp tall, the title moves downward, and the hidden details become visible. The action button is anchored beneath the revealed content. The scene describes motion without requiring another activity.

Keep dimensions and strings in resources as the sample grows. A fixed header height may suit a short card, but a dimension resource gives an English display and a larger Android font more room. Preview both states in the MotionScene editor before running the app.

Add swipe and button interactions

Place an OnSwipe and OnClick inside the transition. An upward drag moves from the compact card to its expanded form, while the action button provides an equivalent path for people who do not use swipe gestures.

<Transition
    android:id="@+id/card_transition"
    motion:constraintSetStart="@id/start"
    motion:constraintSetEnd="@id/end"
    motion:duration="420">

    <OnSwipe
        motion:motionTarget="@id/action"
        motion:dragDirection="dragUp"
        motion:touchAnchorId="@id/action"
        motion:touchAnchorSide="top" />

    <OnClick
        motion:motionTarget="@id/action"
        motion:clickAction="toggle" />
</Transition>

The swipe is anchored to the visible button, and dragUp matches the expanding direction. The scene-level click action toggles between the two constraint sets. For explicit application logic, remove OnClick, attach a listener to binding.action, and call the transition methods directly.

binding.action.setOnClickListener {
    if (binding.cardScene.currentState == R.id.start) {
        binding.cardScene.transitionToEnd()
    } else {
        binding.cardScene.transitionToStart()
    }
}

Use either the declarative or programmatic trigger for a button, not both. Programmatic control is useful when navigation, a ViewModel event, or saved state determines whether the card opens.

Refine movement with keyframes

A transition interpolates directly between two states by default. A keyframe adds an intermediate instruction, which is useful when text fades while the details panel arrives or a header lifts slightly before settling.

<KeyFrameSet>
    <KeyAttribute
        motion:motionTarget="@id/details"
        motion:framePosition="35"
        android:alpha="0" />

    <KeyAttribute
        motion:motionTarget="@id/details"
        motion:framePosition="70"
        android:alpha="1" />

    <KeyAttribute
        motion:motionTarget="@id/title"
        motion:framePosition="50"
        android:translationY="-8dp" />
</KeyFrameSet>

Here, the hidden details reach full opacity at 70 percent of the transition, while the title rises eight density-independent pixels around the midpoint. Key positions are relative to the whole transition, so 50 represents the halfway point. Use them for short accents rather than decorative spins that compete with the content.

Check the animation at several playback speeds. The MotionScene editor can reveal an abrupt alpha change that is difficult to notice on a fast device. If a frame looks wrong, inspect the affected constraint before adding another keyframe; most visual faults originate in the start or end set.

Preserve usable and accessible states

The visible button provides an accessible alternative to dragging, so give it a descriptive label such as “View route details”. If the header is decorative, mark it unimportant for accessibility; if it identifies the destination, provide a content description. Maintain strong contrast for outdoor viewing and large font settings.

Test with the system animator scale disabled, a large font, rotation, and the smallest supported screen. MotionLayout uses property animators, so reduced-motion preferences deserve explicit attention. Where a full transition is inappropriate, jump between the two constraint sets instead of forcing every user through the movement.

For a commercial release in Australia’s market, use Australian English in the interface and configure prices in Australian dollars through Play Console. Localisation can lengthen titles and change line wrapping, so test with the real strings rather than the short placeholders used in the sample.

Troubleshoot and ship the scene

If the card jumps without animating, confirm that the root is MotionLayout, layoutDescription points to the compiled XML, and both constraint sets have stable IDs. A frequent error is deriving a state from a missing layout ID or changing a view’s ID between the sets. Anchoring an action to a hidden view without defining its end-state position causes another common problem.

Use Layout Inspector to verify the view hierarchy and the MotionScene editor to scrub through the transition. The editor’s start and end previews should match the running screen. When code and XML both control one transition, remove the duplicate trigger; otherwise, a click may start two competing movements.

Keep the final interaction measured: the header and text move, the action stays reachable, and the details arrive without shifting unrelated content. Verify the scene across several Android device sizes with a saved trip, café booking, or event listing intended for Google Play’s Australian market. A stable scene then behaves like one continuous interaction rather than a collection of animated properties.