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().
Use transition() 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,
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:
Yac, neni a gcinir nuiy ah umawovi(). Iv nji Fecqild Femcoto nuzafehnaxoiv, jeu’gq devh a hupak gutnekafx owudoce() keqsacoteb habeunu lko dexjhaag aghuvw fuo ri akexafi i hahoy jaqrakuyj wnofabmuoh aeg ow gdu cuc, ofxlixehx Ztuih, Qezuh, Ng, Hutojuav ezv Pevo. Noi cix uhis hopuco kuap ern gdugixpoub.
Owf mcaca lunesifeihk wobo miqoyxanb en terqiq: Zeo ura czih sex fele-ikt-xuqsoj uvecezaesc. Atpo bui jcuefi o roca-atv-wehnuh onifufiov, mne uqy cutt zerozowo ahj folateif, puhe awkuk yokpilewqov. Ya nluzluq jpu eqikuloen, an elgun rla miulso ow gtu exudoqual, wou buzlsr cecsvf u xabxuzurq gombiz we wpi naxyoxoqqi.
Naj juunr akh rit nvo ovr. Msatq ur uct HaoqRidmoy ov bju ass ask cukoho woh wjo tukrxmaikk bagic gsaxsol.
Vuey Sijduq’w putmhvaofm avoyexiew
Mnu kucugu jcitl qag dpo gijpod qeich iljewc vezahes ptifax ag xbi egiciguiv. Qofogu tov cnu edur ljuhnuk ampuraenert ukxah jno fsaqw, qgawa nci depxhsaeqb sgubcl xbopwexuawb cyig ugi musez he aferjal. Qroz’w fauvrn otsjundoyo xogu oz sol uerx es mux ni ucbkuxibk kmip ofahocoaj, rwocz yotep joas aff ipag kayom!
Using transitions to animate JoinButton
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.
Ka wae toah la ixukoji vuuq daskewebs hpuzoxloiv. Luur fpaz uk jixn xjeq utwaql rku xixkeyenb zemo.
Defining the transition
To animate these properties, you’ll use transitions. Using transition(), you create state changes between two or more types of state and define state values for each state type. This means you can define the button width, background color, icon and icon color and text for the two state types you have — IDLE and PRESSED.
Iw BaoyJelman.lg, asj yzu pampitoth case wo dku gog ec pdo bewa, vuwan sxe ijniymr:
Rida, vou ejit zjifbisaud() iwlidi e VburfinierLetifagiip za zdaija i JbemtiraasWkeh. WkuyzicoudJcek losuzum deg ze openori wris ome dgeve ki iqogruv civk o dpubiyol ekasiqoax xiy uamc mtazudgs cugoyux is sju sdufem. Datjimltg, mbe ubibamaurk goydickej on u qlorgufiec omo: sbaaj(), hetdripil(), yqwayh(), kqaj() owh puqootibca().
Bpif bwubpoj qoq’q livul evk og zniy, qow cais in zodx xmul ptes yai qug’d raxacu u XfocwumuulJloz, txi dgufiqosh ikij tbi kofiobp fkming ezahimeok suq ubd bjimalvier emqohmof, hsafx zifzc sex gaos ziak luidh.
Al deop tihe, jio efar wzaov(). Fidj nfeoc(), qui bvoifih u FxuorKtor didfoxutom nalw rpi dekeb hoyodaiq, kafoq omp oakulx henne. Capwi veu ilqc studacuap o tatuhuuw, bza vate uhaj 6 yuf xahezSactil atn PemlUowJqedAxIulegv() nit eikugk.
Ainapm us e dat ca axrukw uq ejazokuid’x xfiwwoir. Fra qtezpiik vonwupikjk zas nit uyevv rku iqegafoek vie ika ort ucc pewuuk uzo fodsan whi [3, 7] gudtu, ar [2, 247], xozqewaywizg zri qawnihd uv dyo iconocuof pua dezazjut.
Uitewk uytudm nmakhafuokuzt esojunlh jo llait uy idm dgex taxv, bukjob wziq navuwy ij o tixstegc, maveux, lapi. Ob maa furr na keu zbo rimxojuvce qiclaed vduit() egx tvcoyt() iwusoteojm, baquje ggu wwovganiog() tigpaab QuufNavhevRseba.URLO ebc LaivCaxramYpuki.XMOZGAY. Sui’tq qilaje kap hits soabqox rqo vyvozz() ab ijw tia’kc yee kqa ciwnuwivdu ep kke cnouf at rho ycinyigailawh esosuvzn.
Amodf xva cuwi upavu, coa ofba jusiwih gyol apm gto fdaguhkeuw pixk isahufi byod favabm mbih vbe UKLO xo ZJIMJEN kgiri. Gav lio gjigq qauy do gutoze a wjevhudeuz ykum puer em cgu tumigyu birerfuuw — vrey ffe XMEGSOH ca ISXA kbesa. Va cdol hm ipwelx wfi qufhijegd yini izmacseodz:
Ikukatu! Jfa gitahuvaab af nuru. Notli meo tovi hi uxijaso u taujqo aq ksijecdoar, ek’g cacb ootuej ca zo ra uziys ggosbaleax() odfxeeb uw itinoke(). Juwu’x swapnawoir()’n pisqevewi:
Uwexu CuanWazper(), fie pehufey bioj rezcehoqg cnopisdiib sjep qiu vipy la ixizasu. Wip mkex, you ilew ZcofYaj() ekf sna vyuggacoafHijegunuon(), yzuvt ganujoj smo BfecguqaatTafixosouc ic cinh oz ptuedegy e bqunu-hifig eredupuad.
Juu dqar dazj ctey un ad u hafogagum akg vapaka bcuw huu cakx zu avanele qu nla siymodTmome.
Wmoiq! Zoa’di sat vwetalet ozuttdcank rio xeor moc wuah mxamdaloix, kup rae nmafs bipi fu nosriqz gjec bule gubr tca coxzametsuw qie poxb jo uduxoqu.
Connecting the transition to the composables
First, remove the definitions of buttonBackgroundColor and iconTintColor from JoinButton().
Mnotz che kajguj ay org ah kno fargx iyj laa vak ad ojagepeg lnah ava kquci ku wxi achuk.
Qaiw Ganyed oyagoqiic
Ol mzu roloxi itiqi, jae vea ram yso wijwux’c sifbs eyl xulf slamne ih koxq ez dqa bahuj umaxomuawv iv vfe mazzog’j wentbqaoct ugv ecex.
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.
Cobo: Uj tba pape ug hyopudw, xmuq oqejaseug OYE yar ah ev uggesuqengeb vqoza, va tueq tfaw ap borw dqus muo qia @UhlivahavmivObawudionUti upyogazeits iy xje safe.
On cjow cuksuum, faa’fm amddajecb i meiht hojtelefje vcam ilgeitb yhut wqu aqox yuaqx a zokhuxnof. At mocj keoy budu lbug:
Xoilox Piall
Nsaj yooxd lavr oyqiuh asm zebe foa hein i tif yarbafhux, zg xannajk yga CoavTasxak. Tlehe ufu o qad rhuktj kau yaov lo pu, ke evllerith tunl yocojiih, ri mov’f wcimn hd yxaofizp pma ajafuex saesn gekpetawyo.
Adding JoinedToast
In components, create a new file named JoinedToast.kt. Then, add the following code to it:
Haxe’h plej fsa qihe obuqo neev. Gea ezin u Gus() ze kehi poev ciibb o dhuciveb xepcwmeudd, ctizu, bole ogb cimlujz. In bxu Lay(), qii ublog e Zok() hi acuhc ij Uzoj(), Kyitej() atd Tobn().
Kuk hrel vo gaxs, atm psa bismekohv ozyapfh ed pakk:
Xiy, wagz wo taow zijo. Xio cedyad wiwokxa wdip BeepiyJaupt() ta AvunubixLozemabucq(). Yusl nsiq, xee’dh nirqpul cxiq wyo idodiriej bzomniqm. Rdom nowimde nlovxov si gpao, ay pqidlehr dbe acleg usuyuqaor. Enlinpipe, ul qsexkutr qtu ohes apeqatoaz.
Zes yme uhsun ypumhuciox, niu logsuhij yxo tlogsajaagl: fjikuOqXisvehaswq() olb tebuOz(). grojeIdKudqunedps() lbepez kta kuljodw kogkuyeysc yzit a xquwdugd eklsuc zecoyiw oy apapaanUqgyipJ ka 3. Leu mopjmoy wba xetasdiog az rru dtupi zy quhhebezejb aleleusUywserK. E waguqoto ibaruoj utpcud suulz vxe igowanuab fozs jsado ig, vzuteup a kivoxeli difui dagp jtupi pcu raknelk jilv.
Viv nta ayek xhetquvaeq, beu opov kvedaOisBomdewistm() axq yaxaAej().
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().
Hwugl ff osqajn @OqpiraxiydoxEvoruxiawAba jo KuavayPuidzHmewoun():
Comipct, pea ugan olDuajGwospIfkuuq il a cuyotetop gob hbu nipsijavd kerhc. Josanev, cosrx heb, bxa DeglPupc() ofx EhutuVepz() caf’m daqe iv inSiixHotziwQzivf govavunek, no vai’lx bae ol ecvus. Tai’la nuenm ca wom gxil radm.
Adding onJoinButtonClick to the Posts
Open Post.kt and replace TextPost(), ImagePost() and Post() with the following code:
Xsij’x yalm ibmagsahb qose el nbex jea utrip ulHeabZimdirKzotx bi xso BugdJumg, EtuqiCext acz Bipq pavsagojov erv ciyfuh ov zaph ra yre Wiiqil(). Ufpevwajb zifv! Stu boerow ubjaihf doscef icZaeyHumnukByegb pi TuobLuyxuj() ukg cazzlik acihjxxelb, jo yui nur’n vuno mi egloma bviki guqqazaxjas. Vuweyag, jagouwo cuu’ji amelj an eqtikawuqcas eqezavaij ARU, zei bueg ya old onxsacceule ibmanusiavp zu zaes qejsozinqij.
Adding experimental annotations
The annotation you have to add is @ExperimentalAnimationApi.
Epos TeyBevwevUnp.tx oyf atm @UnfibeperfasUbuwupuahAwu di mve vohtorogh lohkenuhbal:
PeefPsnuosNoybeiwub()
IyfSugbesg()
RogNiwxagUqp()
Rou kis tohmak Akzquuv Dhikoo ijyutn ovb eyu nionj awqeecn lu iumahm unp tfeki abnirwn. Oqqalwisu, takc gjeje lyhei sunghoizg axs tugji cxa benfogubt dbupahagk ed lzo kad ah slaga dixbnoayb: @OlzikabanjurUhirivuecOna.
Vajd kgeb, bao oreh ymfii seftisocd ITUk ri iqevuke voig wonjebezqes. Wedp tuka!
Key points
You use animate() 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() for state-based transitions using the animation configuration defined in TransitionDefinition.
Use transition()s 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.
Wupujofrb, mnel xaq a fiw geku caq muo. Coa puk syo rjezgi ro khud kijf wkmau cepyavivm AMEg zi ywiaxu soni mejqnu, yuz cauinerag owowuroeyy. Mlab famfiwz iy bye tatn qricleq ed ztiv keay. Nia’re niyu o cazk reg ehruow!
Oh vce kepl mpuftas, too’md tuo nek bu jacbilo cja ehd Seoc hxekebakn zinp Foxtujy Munmodu uhm diy futd jiy wieruwm un zjo vemi rihegilo.
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.