Animating Pressed State Using Repeatable
Last, but not least, you'll give a final touch to the idle state of the button to draw the user's attention. Open AnimPropKeys.kt file and add:
val idleHeartIconSize = DpPropKey()
Then, open AnimatedFavButton.kt and, in both the idle and pressed states, add:
this[idleHeartIconSize] = 24.dp
Add the following code to the transition from pressed to idle:
idleHeartIconSize using repeatable( // 1
animation = keyframes { //2
durationMillis = 2000
24.dp at 1400
12.dp at 1500
24.dp at 1600
12.dp at 1700
},
iterations = Infinite
) //3
There is a lot happening here in this small chunk of code, so let's see what it does:
- You define an animation builder for your newly added property key of
repeatable
. This builder allows the animation to be repeated certain number of times.
- You describe the animation that will be repeated, using keyframes.
- You set the number of iterations as
Infinite
because you want this animation to repeat itself constantly. This parameter also accepts integer values, in case you want to just repeat the animation a specific number of times.
Now, open ButtonContent.kt file and replace the modifier
in the favorite border icon with:
Icon(
tint = state[textColor],
asset = Icons.Default.FavoriteBorder,
modifier = Modifier.size(state[idleHeartIconSize]) // here
)
By reading the state from the idleHeartIconSize
, Jetpack Compose Animations will constantly update the size of the icon, making it smaller and bigger, and simulating a heartbeat!
Build and run your app. Now your app's idle state shows a beautiful beating heart, luring your users to press the button!
Where to Go From Here?
You can download the final version of this project using the Download Materials button at the top or bottom of this tutorial.
Great job completing this tutorial! It wasn't easy but you've learned a lot and now can harness the full power of animations in Jetpack Compose Animations and start putting the cherry on top on those apps of yours. :]
Jetpack Compose is still in developer preview, so your best bet to always be updated on new features or breaking changes is with the official Jetpack Compose documentation. You can also head over to the official examples repository from Google, to check out beautiful applications done fully in Jetpack Compose!
If you have any questions, comments, or want to showcase more beautiful animations, feel free to join the discussion below!