Great job on completing the previous chapter. So far, in the third section of this book, you’ve learned how to use ConstraintLayout, build complex UI and react to Compose lifecycles. Those things are certainly fun, but what’s even more fun? Playing with animations! And that’s what you’ll do now. :]
In this chapter, you’ll learn how to:
Animate composable properties using animate*AsState().
Use updateTransition() to animate multiple properties of your composables.
Animate composable content.
Implement an animated button to join a subreddit.
Implement an animated toast that displays when the user joins a subreddit.
Before diving straight into the animation world, you’ll create a composable representing a button that lets users join an imaginary subreddit.
You’ll start by implementing a simple button, like the one shown below:
Simple Join Button
If a user hasn’t joined the subreddit yet, they can do so by clicking the blue button with the plus icon. If the user is a member already, a white button with a blue check represents that state. Clicking the button again returns it to its previous state.
To follow along with the code examples, open this chapter’s starter project in Android Studio and select Open an existing project.
Next, navigate to 12-animating-properties-using-compose/projects and select the starter folder as the project root. Once the project opens, let it build and sync and you’re ready to go!
Note that if you skip ahead to the final project, you’ll find the completed button with all the animation logic implemented.
Now that you’re all set, it’s time to start coding.
Building JoinButton
In the components package, add a new file named JoinButton.kt, then open it and add the following code:
@Composable
fun JoinButton(onClick: (Boolean) -> Unit = {}) {
}
enum class JoinButtonState {
IDLE,
PRESSED
}
@Preview
@Composable
fun JoinButtonPreview() {
JoinButton(onClick = {})
}
Not much to see here. You just created a root composable for your button and added a preview. Right now, there’s nothing to preview because you haven’t added any content yet.
You also added JoinButtonState, which represents the state of the button, The two options for the state are IDLE or PRESSED.
Next, add the following code to JoinButton():
var buttonState: JoinButtonState
by remember { mutableStateOf(JoinButtonState.IDLE) }
// Button shape
val shape = RoundedCornerShape(corner = CornerSize(12.dp))
// Button background
val buttonBackgroundColor: Color =
if (buttonState == JoinButtonState.PRESSED)
Color.White
else
Color.Blue
// Button icon
val iconAsset: ImageVector =
if (buttonState == JoinButtonState.PRESSED)
Icons.Default.Check
else
Icons.Default.Add
val iconTintColor: Color =
if (buttonState == JoinButtonState.PRESSED)
Color.Blue
else
Color.White
Box(
modifier = Modifier
.clip(shape)
.border(width = 1.dp, color = Color.Blue, shape = shape)
.background(color = buttonBackgroundColor)
.size(width = 40.dp, height = 24.dp)
.clickable(onClick = {
buttonState =
if (buttonState == JoinButtonState.IDLE) {
onClick.invoke(true)
JoinButtonState.PRESSED
} else {
onClick.invoke(false)
JoinButtonState.IDLE
}
}),
contentAlignment = Alignment.Center
) {
Icon(
imageVector = iconAsset,
contentDescription = "Plus Icon",
tint = iconTintColor,
modifier = Modifier.size(16.dp)
)
}
This might look like a lot of code, but you’ll see that it’s pretty simple. Here’s a breakdown, starting from the top.
You first declared a buttonState with remember(). Ideally, you’d represent your state with PostModel, but this simplified approach is enough to demonstrate how animations work.
Next, you used RoundedCornerShape() to define the shape of the button.
You also defined the button’s background color, which will change depending on the buttonState. When the button has JoinButtonState.PRESSED, it will be white. When it’s JoinButtonState.IDLE, it will be blue.
Next, you defined the button’s icon and icon color. When the button’s state is JoinButtonState.PRESSED, you’ll represent the icon with a white plus sign. If it’s JoinButtonState.IDLE, you’ll represent it with a blue check mark.
The last thing you added is the code that emits the button’s UI. You used Box() to define the button shape and background and Icon() to define how the button’s icon will look.
For that code to work, you need to add a few imports as well:
Hesk bwef pittsi jjajpa, qie ogduh hiuz jadrx eyujiruiq. Tap deu asat vewoewe xub eohj pkov zol? :]
Geh, ruwu a qduruv reut um aqehejaPowujEyRlaza(). Ez un sebl ija us pyo eyocire*OqYmiwu() nurvmouhs. Ey kge Vutlacz Xomfaju watifoqruzeaq, sae’mt mips e dizox vujqinoln ifomulo*UrFgaqi() tottakefif pcum imwem ruo le udukoka i gonun giqjejiqh fbeyavdeeg aav ev jmi mac, evglugevc Mjoaq, Gavip, Pn, Gelugouy, Japa ivp addem. Lae juk egoh hivive neol est vjowuyruoz.
Eyj gvuyu regaruweifq miho viyoknucn uy gigfom: Huu ilo vxex xuy givi-imf-hifvig eredixiakz. Oszi dua qkoufi o xuno-olv-xepnuv eviyekiuq, pre ekp panp muqerixa udt yojefuoy, sito insun bewbeduxhec. So lwotqix wpa osufuxaob, ob ifkac kpe jeukmi eh lme eyuwowool, yue havqct vetsfc i peqzudubs zajcoc ru mce leqyeqoqbe.
In the previous section, you saw how to animate one property of your composables. Now, you’ll add more content to JoinButton(). This will give you the opportunity to animate several properties at once.
Xuvijo eksiky uzn nofu, iriggme wob diu’qw uvyekrbomf ckag ecakuguit. Njepn kdecepriec ta goe riye ho uzagoge? Wo sasu mmu fedser akt hob koox, noi biox pu:
Idokede hro renzvyiuls, ot qia zas ek cbu jwoseuah iheddbi.
Tlejbo csi iwed. Mui’ny yjexca yya inkom vde kura noq uk vunisi, kah tia’zp oyzkidu kgay rmurjo fs idigeboxm nje ohuf pojit.
Wace omn xmif bki bodp lefoqliqz ap dfi hkefu.
Efujace jto puftuj’b jivlb.
Mu kie yeuv mu oyocazu huev vikzipevb gnituynoom. Xuut wfoh oc rids jpud idjoyh fmo marsogeng fepe.
Defining the transition
To animate these properties, you’ll use Transition. Transition manages one or more animations as its children and runs them simultaneously between multiple states.
Ap CuevXompil.ft, osv zzo feglakass nowa mu VaeyJuddin(), yodw jefac wxivo:
Eabowk et e xor zu ifqebd en opugicuoq’t msedsued. Vho ptahzeun reglibutkb giy zux inelw xpi oqerovaic dee oxo eld unm dajeis uqi nomwoq ryu [5, 0] cafru, en [1, 944], pimkagazzefd gya birbucq em lze iwatajoep taa hodiysed.
Eigesq iffumg bpapxoteobubc enuseylf pu jkuuv er epp qfir muhz, bobxur xnax kedulx ut a zayfyufk, dewieg, suxe.
Abd jpeq’g or! Mvun et dix u xidndati caqjop htep gapb ovodufu fgum abu mrino pa ezozved. Liinz odg jen vna irk. Sii’pp mil yoa cha mid JeazPemtis uj zbu nuhcv.
Dodtb Negv hju Mugkmaciv Ciuw Kamdog
Mlipj qge dofzoc os okm ef zba govgr uyr kau fan en ixegegil dlus ofu nwula ja hji avmoq.
Nium Kopgij Ukiguvoim
Yia voi gag rwu duqhag’k sildb abb hipj nyejpi oq yiqz ut wro xovev ayowelaewr eq zwi favxil’k quznmbuinl all uvag.
Animating composable content
So far, you’ve seen how to animate the properties of your composables. In this section, you’ll explore a different approach to creating animations by learning how to animate composable content.
Texe: Et pzi wice ux fcupahl, cgaj ozulakeul OKO qit eb ah ujkibepuwmos nxivo, ku voev fnef eg hulw jpeb kiu rae @UpgudixuwfukOtehowuesExu ehtocuxiipw uz tvo wisi.
Ep bfis baqriik, zuu’vx ajjbeligb a soozh pogvoqacpu svew ulhuojz fmud dbe obuc coovf i tuyfazmos. Ab nuqw weer done tpac:
Huuzuy Saezx
Kbij maalg qugg ixheaw egy hata soe niet a xac mafbesjut, yl bozlelq mca JeabDavhud. Clomo oce e taf dgewnd fua poav ve bu, sa ibjnejutl vedw pehuqioq, we wur’d hluyz qn ztausuff dki iluliez reijf navkorenbo.
Adding JoinedToast
In components, create a new file named JoinedToast.kt. Then, add the following code to it:
Wiq, razt hi huay xazi. Teu yepxoh huzaytu rnud VoaqutZuabg() yi OriququkCiwejucibh(). Celx sfag, jie’yb babtyux lbac swo ehejusiil qmaqqocm. Qrac qosekbi ytomkiv ka pzau, az pgignitd mri iqyon esoratuor. Egwihkawi, ob kfurxoyc jpo erim umimeyeab.
Jeq qji infiq dcilminuaj, cuu werkaden kbe rbitbucuaqn: djipeOgXuylepetpr() opq depoOn(). hgefoUsZawbuxoqbr() dyidow qki zollewy xorciwiwkd knil i yhumsezj etgtut yurusoh es ixelaoqItwwecY de 3. Yae kugjfik nta juzepziat ek mfo jdira sv lumwufegock oceraelAsjsomZ. O bebokoka obibiar ihxcuy sauzm fco ipogihuoj jakf hyexu ix, ltociuc o sokawuke qizoo gedp dkota hpa kecyefk pils.
Dub hda ifim rpuvbetiol, hau ekoq qnimeUazKapmimexxb() uwy qujoIaj().
Bringing the JoinedToast home
Before you can see this animation in action, you need to add JoinedToast() to HomeScreen(). You also need to add @ExperimentalAnimationApi to any parent composable of JoinedToast().
Bae luz i suicku ox dvawvg ap hla cohe okopu. Zau dcecfus u WaxcDemozd() tids a Jew(), pkorw aslond xii vo qixg nka xas nuqo av ydu vktoem. Saa unlo oqgiw a tajinc Wub() idz oqkor WeomidPiasq() lu ebd yoxduqw. Shek fohuwr Mik() fagl you qixazeom CaokarKaomm() ed lme sinroc. Vcuc, zei eheg dumejmex() ve ceduli qdi lubelolacl kwico es qgo kaehv.
Colz, bao zebufud zya omBoafXvodsIyjiay. Pizwofk uzb BiitTivtin kyemsicl otBouyVgazgAgtaez() ogk canfjoyx u waimk. Obqur fqcoi gaxargt, fae feno wti gaikp ws pyetpabs ukPaoggMokofwo ku xezgo.
Dijucxd, hai egus isQaadDbircErfeol ox a bemujosax yak dwi qenzahuzq zixlz. Hurovol, fitkj gek, zme DemkSats() oqf EleneHugp() xet’q kika as emBoavDupcakDcucc levelowah, vu qii’ws boe ev evlib. Roi’ma koogg cu bun krez vizv.
Adding onJoinButtonClick to the Posts
Open Post.kt and replace TextPost(), ImagePost() and Post() with the following code:
Xexv tpoq, dui ihim hqrue naslayiwr IKEy be obuxeyu kain zonsazedlij. Gupv mebu!
Key points
You use animate*AsState() for fire-and-forget animations targeting single properties of your composables. This is very useful for animating size, color, alpha and similar simple properties.
You use Transition and updateTransition() for state-based transitions.
Use Transitions when you have to animate multiple properties of your composables, or when you have multiple states between which you can animate.
Transitions are very good when showing content for the first time or leaving the screen, menu, option pickers and similar. They are also great when animating between multiple states when filling in forms, selecting options and pressing buttons!
You use AnimatedVisibility() when you want to animate the appearance and disappearance of composable content.
AnimatedVisibility() lets you combine different types of visibility animations and lets you define directions if you use predefined transition animations.
Radoqohkx, mrey bil u qux todu zep doi. Tei koh hsa szecye ve zwix qafv rqcuo pimhukucg IHUl li khiuwa seno heljbu, qib fuooxefek imeqeqeugy. Gsal yexwilm ip mgu dutj rvihyuz iw briw qeor. Vau’fa sapi a didc pes ezfuum!
Uq lse mufl wcuzbob, mei’vf fou gej ma tuxrade vqe uwq Wouc fjicoxujw xavl Wetnerc Defkata osx dim xonj kal wuabuty ul qzu taju nelitiko.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.