Compose Animation

ビジビリティをアニメーションさせる #

var visible by remember {mutableStateOf(true)}
Column {
    Button(onClick={visible=!visible}) {
        Text("Click.)
    }

AnimatedVisibility(visible) {
    CatIcon()
}
}

Contentの切り替え #

Row {
    var count by remenber { mutableStateOf(0) }
    Button(onClick = {count++}) {
        Text("Add")
    }
    AnimatedContent(targetState = count) { targetCount ->
        Text("Count: $targetCount")
    }
}

カスタマイズ #

AnimatedVisibility (
    visible = visible,
    enter = fadeIn() + scaleIn(),
    exit = fadeOut() + scaleOut()
) {...}
AnimatedCOntent (
    targetState = ...,
    transitionSpec = {
        fadeIn() + scaleIn() with fadeOut() + scaleOut()
    }
) { targetState -> ...
}
fadeIn()
slideIn()
scaleIn()
fadeOut()
slideOut()
scaleOut()

(https://developer.android.com/jetpack/compose/animation)

Animate a single value #

val offsetX by animateDpAsState (
    if (isOn) 512.dp else 0.dp
)

animation Spec

spring
tween
val offsetX by animateDpAsState (
    targetValue = if (isOn) 512.dp else 0.dp,
    animationSpec = tween(durationMillis=3000)
)

複数のパラメータを同時に #

private enum clas BoxState {
    Small,
    Large
}

var boxState by remember {mutableStateOf(BoxState.Small)}
val transition = updateTransition(
    targeState = boxState,
    label = "Box Transition"
)

val color by transition.animateColor(label="color") {state ->
    when (state) {
        BoxState.Small -> Blue
        BoxState.Large -> Orange
    }
}

val size by transition.animateDp(label="Size") { state ->
    when (state) {
        BoxState.Small -> 32.dp
        BoxState.Large -> 128.dp
    }
}

https://www.youtube.com/watch?v=Z_T1bVjhMLk

API Reference #

https://developer.android.com/jetpack/androidx/releases/compose-animation

https://www.jetpackcompose.net/jetpack-compose-animations