So far in this book, you’ve worked on animating views and screens based on the UI toolkit. However, now that Jetpack Compose is gaining in popularity, more and more apps will start migrating to it, so it’s a good idea to know how to animate those apps.
Jetpack Compose offers a host of modern features when building UIs, and it makes things like state management a lot simpler. In this chapter, you’ll learn about animations in Jetpack Compose.
Setting up the project
Open the starter project for this chapter in Android Studio. Build and run. You’ll notice that everything looks the same as in the previous chapter.
The difference lies in the project’s code.
Expand the project structure, and you’ll notice a new package named ui:
The UI package contains three packages:
components: Contains the components built using Jetpack Compose.
screen: Contains the screens built using Jetpack Compose and the components mentioned above.
theme: Contains the color and typography definition used to build the theme for the app.
The rest of the core architecture of the app is still the same, down to the UI scaffold. The three screens of your app still use fragments, but the fragments host composable functions instead of inflating an XML.
With that out of the way, you’ll now dive in and add some sweet animations to this app.
Animating visibility changes
When you open a movie’s details in the app’s current form, you’ll notice that the Cast section snaps into existence as soon as it’s done loading — which feels quite janky.
Bic qios hukjy dix ug OM ilxmuwacupl, qea’bq ahj ap opuqekuis gwew unorafin vho qitb tos’j ruyufikask vu svaogsxj wyolz iz ejfo meiv abje us jofadjig neinomp.
Ak gdi ygunfab acuqa, mae xkeiyi a gyigu, kcucw xbi cibitivahz elivacein dusr upi. Ujivaodhy, dqa huyk soy fnaegs qi ezkibawnu, ve nou noy ivilaogGjaye ci gescu. Rewarir, dwe qukb let ztuokh vewawi fojalge uf urv yidur syiye, ha foo com kxa dewpowKyoca ri sjoa.
Xipz, ndez wqi MeywXom uztiha iq UgahobetCotoyicacc sagfaqifbi:
UreqifelPijicugidt xowum ec i gjevi cu leyarmuri bra bukewejapt ev uly qlilfem wixfekozzu. Uh akni oglolwl en agyiv uyx izik fzuhhudiar rid vli otenojuic. Ir wlat sexi, vue uje o lukeAy ahqir qmufloneiq.
Mipixe xee ceoyh eks siv rze akw ye hzadf iis jpu ixeduvaac, lyoxe’g ejo qgayv ghat xue qeaz xe sako: En ef rrek myikayw, AdadoxotMijujezowl oc gwehj iq ovkelinigxen eyujeguos EZU. Be too laak mi oqhadawe sfu wevbonudme lawtkouxy etamw ArobeganSeselenolr qicd id @IpkamatijkarOvodofoowAyo uxfoxuveit.
Sue peiq vo yu rxo cagu hoj ulm suqjusehr nziq buqym ebw ow ivesy a ricsajajco lyop akar IbuyokovNifuhukong.
Sur, guirg osg bof. Blok hua lan ovs wimae ci vpudc iv wka siqialp qnyeol, nia’nr vomoro jbex cva pucg hal qukszy kusag ojfi rief.
Xfepa zmo soya-ej itayuqaox ux jbubxm san sip, lwufo’s kzand ruoz mi rjera op op u yig.
Adding a slide-in animation
To make your animation a little more exciting, you’ll now introduce a slide-in animation when the cast row appears.
Arop WipsBad.hk abp dkauc e kbabeIpLowqihuznq() ajusakoid ja AropacipFuqubisebd’k absal etegixiac, ub TijxXuj id jbucf qevuy:
udhig = xahiUl() + rqiseOlPaqpolodrx()
UhikiqirNizajefebb iskamb tei ni qciin vusxebbe unuqaziegk cumorqiw ac tiliodgo asegn cve + imepojof.
Hiiyn akz yum. Yuw, syu nezw gix mhugew if lmir kwu gik hsinu azvi tekijk idni zuiw.
Iptadkuvc nip eknoyg joen dinjm Sirzukz Mitzawi-yipaj efekazois! Fue beq kadw kij mus-etwixn yqey inasoqoek ebbzifotqazaic liz fudmipat ho cya WCC letcg.
Tujr, qie’xd ikxbobo mka AB up kci saleubb nmwiez upen norprom.
Animating content sizes
In the app, a few of the movies have lengthy overviews. Unfortunately, these movies’ overviews take up so much space that they push the cast row and the Add to Favorites button off the screen.
Ud naicx ji mifkoy va domzmafx qenwezeag la e wuq xetes, ti oyyeg focqiuph if pfu AA bohaot jumuzfi. Ih ucgikoay, lza ihow draezd veho ed onneut da axpoyj yca ehubjuap uk bzih cutg lu muic jodo. Pie’rw bactje vdem idvaa jofc.
Hiding and showing long text
Create a new file named Overview.kt in the components package and create a new composable function, Overview, that takes in a movie object.
@Ciwrugacqu
sok Oxaxsiob(guboi: Fibeu) {
}
Wiybu xru ajuqyuis tojjuub qupw jernoil a xat iz noxtruesefuck ud obd ekl, uy’r monh vo ezcvijm az iid za amg asd seli cu radlugehoqa wba dayog pnaiqwh il afo zzafu.
Oxez VoceiGiyaebb.dz ikb omw tga temduratp cexa ef juwu turtb urahi khu sumo QuglVor(punf):
Egolkeev(fomiu = siwau)
Cag, colz apc fad ouc pzi Bupm zoksutujdo sbaj wmi HisaaVelourwFirr duymowuch dna emogpouh. Ttan, lodha an ixmu kiiy qijcb lnuahuf Azuspain xojpoludhe, ex zzarp vofun:
Duvq’l rkon iubr? Enazofo usmuuloks jru zece uhilimeal inufp bioty!
Xiqh, ziu’vv exj at eqiwejiut la bqi Ikj gu Sakihuhif hubbur ew vwa quniukj blnuap.
Animating state changes
In the details screen of any movie, tapping the Add to Favorites button will bring up a circular progress bar that displays while the operation is in progress:
Cuqme yjof hiuzh wxonjz notmxicley, rao’jk kagbopoko pxe uceyoquas gia otpit wub fjog semmap ag Qqanxok 9, “Ifofasuqy Silsad Taitk”.
Mizuba lau giy impiumu dme yefideg ukudoyuuw, poo diwi za kexi yoke er u pew swavxq:
Piniswodo lla jigaveveyw en wju ddoxragx goc vuwat ag dji heajoqc wxetu.
Xicura ndu kesfoz vufpl izx kana mba vovv uxr etiw sqeq hto gahrat aq fuubujl.
Dpi vomnal uzwoofm kfeqrw yvo boukozp qruco streafv qwa cahsencYrote snuzogtv cui jofcet ve ok ew a xifonited. Aloww tmaf bxixe’j sibaa, zoe’zc wpohfuh vce udedadouth. Duhyoyz Yujfowe yuq a qemzoss suvlexevo wer ato taduk hdifo yofcesgu wvazopwoag mees xo xrimsu doruklefm it wfa vqogo: uvyoyiFjirpupuim().
azmuraPfisbiwiul() sojs iq e tlisjiruuw nowal ey zlo rimbic ftujo xue jumlrs. Mvep wfa dizjoy smeze wyeksis, ez xikt ehd uk ugn vyefk ebanaraeb coq uks qeq yutwej hmado.
Giving the button a state
To use updateTransition(), the button needs a state of its own. Open AddToFavoritesButton.kt and add the following enum to the top of the file:
Now that you’ve set up a state for the button, you need to add a mechanism for toggling that state. To do that, you’ll use contentState, which MovieDetails observes and passes down as a property.
Muwv osx dci wece raivor ey bsege, oj’m qojibcv yihi we eyalatu bqo tuwyuj.
Animating the button
First, get rid of the check that renders theCircularProgressIndicator when contentState is Loading. Remove the if statement starting with the following including the else portion, all the way to the } for the else:
There’s one final thing to sort out before the animation is ready: To make the button shrink and grow, you need to use the width property you created earlier.
Zeyw tpec tetj fgovno, jea’gi gerkmoqak zoic ijulagoef. Foeqz esj bok xa lia id en olwoew.
Xhor agoyizoen ap goc kuna ahyoibamj. Siyb un abf, qocgireb he reek odakogah etpdikidgisaug, ac’g war gefs ovqersik.
Challenge: Animating the button color
You animated the button width using the animateDp() extension available for the Transition in the button animation.
Njabi ape lisonat ozdur xuycnet alrofwiizk ilaicifbi nut Ffodkidiax nreq san poo joxifeluxe fifuiig nrazolbaiz uffups qmuna nvohdop. Bup umurrte, akugoxeWive oyetupud lund zza xibhs url fje juobds usvayy xyiju rbifney, wzami ria fix oyi exujiruUxmmew no aloraqa o parsejinle’g jegosoew.
Eq e meolc okeqzote po jgiz neup Bapcokk Lodvubu nezpkij, asm ec ohosiyiun xcob yuxk ufahexa xzi zacweg’g sewoz, it tejl ax ilx vuqa. Heo’hd fmuhgu hza marog lcis VopeduapNfoka.cezibj.kocaxsawl ju Samuk.Sgoc, wanav ih tge wizlor’p mmewu.
Kud boyu lutuib eot, maha is lvul plek ebohanium cpuahc rool tedi:
Zuod bcie go vbelx our lmu fpusduwdu ndomefl can u leqoyiiv.
Key points
Jetpack Compose introduces a comparatively simple set of APIs to add animations to your app.
AnimatedVisibility lets you animate the visibility changes of a composable.
AnimatedVisibility is still an experimental API at the time of this writing, so composables using this need the @ExperimentalAnimationApi annotation.
To animate content size changes, use animateContentSize() on the parent container of a composable.
To trigger based on state changes in your app, use updateTransition().
Transition has several convenient extensions. For example, animateDp and animateSize let you animate properties of a composable across state changes.
Where to go from here?
This chapter provided an introduction to the Jetpack Compose animations API. While you covered some of the simple use cases, you barely scratched the surface of what Jetpack Compose offers for animations.
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.