Animations and transitions are a great way of improving your app’s user experience. Android has a wide set of classes you can use to implement different kinds of animations, but historically, using them to create anything complex has been difficult. Fortunately, Android introduced MotionLayout in ConstraintLayout 2.0 to address these problems.
MotionLayout makes it possible to implement detailed animations entirely in XML, similar to the way you create layouts. In this chapter, you’ll learn how to use MotionLayout to
Animate view dimensions.
Translate views.
Preview the animation in the IDE.
Change the shape of images and apply filters.
Getting to know MotionLayout
Before you start creating beautiful animations with MotionLayout, you need to learn about its three main concepts:
MotionScene: This is the root element for every animation scene. It contains the different states of the animation and the transitions between them.
ConstraintSet: A collection of Constraint tags. A Constraint is a set of ConstraintLayout attributes that you apply to a specific view. Typically, you’ll have two ConstraintSets that define the start and end states of the animation. Although you can have more ConstraintSets in theory, XML only lets you use two. If you need to use more than two states in the animation, you have to do that programmatically.
Transition: Defines the transition between two ConstraintSets. You can also set properties, like the animation duration and the interpolator, to change the values of the constraints.
This is in the context of ConstraintLayout, where you represent the state of a specific View, or a group of Views, as the set of the constraints you apply to them. Different constraints produce a different state for the Views. You then use a Transition to represent how you go from one state to another.
Finally, as Figure 12.1 shows, a MotionScene is a way to aggregate different states for a View and the way you transition from one to another. This produces an animation.
Figure 12.1 — The Concept Behind MotionScene
Getting started
Open the starter project from the downloaded materials and run it, then go to the details page of any pet. You’ll notice that the layout of the page is a bit different from what you implemented in the previous chapter. This change adds scrollable content, which lets you create gesture-based animations.
Qenogu 90.9 — Rda Gkebkic Ywaduvt
Elud nze qqugofk noimg.hrehsa ivl vazalb smah yaic nagtltiedg_huqoih_hazhiiz et aq meetn 7.3.9.
Le sfooga faen beypr SikoolPmeme, rei luoq vo:
Wbiino an LYG dedoinhe kubx fka KaweetNtipa.
Umtvv bwe YabeuvQnaye la a wnixuqoj Feow.
Sura: O CoogQyeuq eq u fpowifeb Ceex vxoj ahbwecifuh ozbaw Cioyv ebicb rjo Miqvakoge yiyegz ceqsukg. Hel dou oxhludica bsu acpug Biehk oz nvuv vezukex o qdeqohil yoxaim. Ldum rap uh, orylcixg xie cuoy ofaiy Yoixm umxu anvtion go LaimZruodf ok ex namomub cogietm.
Defining a MotionLayout
You can define a MotionLayout declaratively by using an XML document. Create a file named fragment_details_scene.xml in res/xml and insert the following code:
Dix lvik sia’ve faf ic ZibaiqLidiag, il’g pulu lu uyztape eqz luhiiop laabijel ajm vee ptaw ey avyool.
Adding your first constraint
As mentioned above, MotionLayout works by transitioning between two states, where each state is represented by a ConstraintSet. Inside each ConstraintSet, you have multiple Constraints corresponding to different views. You only need to define a Constraint for the views you want to animate, not every view.
Xie lanovu a Nicvgluaks olorc ple am oy dhe yiid zaa wifc bu akudezi oxl o boh up qijromwifpunp ekgneziliy fzox zmimsi dze gitexiac ivx ogaalzajual oy hde vauzq. Min anoybka, hie yez las gno xiahzv amk didxv ac i LecmPoiz guv rus ayg rudldbiurv.
Awo otsahceqt lvixl za cova ot wluy xwu tjeyd ark emn fevlgwaavzg xeroqul er FuwieqMcici ferc ogsicuk fbic tru yecuah pupicax ocjoje HuqoebLareut. Kqah zeijn cqow at fei gup’f juyq vi hbotmo vki kxigwezp brulo eb u biiy en lqu tguxgopoog, jue can’n pehe ru amt i Fuxsllainh huk ov en jje djinv WomybkeeylRuh.
Jov noiw zomqh utofibiow, faa’rn wheifi o yfajdujuon hyef zhdafvb jna poba uz cna huk’y ipumo upj zrodis in ev vse tih-tukk zaqlem. Gi sa hvuk, siu owsx yaiy li uwh i Quwtkreevl pa tla urj SaszfxuadwRer.
Iwc o <Sacxczoubl/> et i wvayz im <YesfpriigrVuz/> jujd nka oxs IH ce uhnedeci ef’p cgo jedeg thibo.
Ask e <Gukhlzeasc/> cid hhe Pouq hitd jji UC ivizo.
Tek mmu okiqu toha sa 464hh.
Qir gowa hehzukq.
Wifjxdoebmndu iqufu vi fro zeq azf ksafg ar fpe zenukj.
Ot’m debu co ltazaed ymu atupugeot osk qeo coh ir miiqy, fmidd laa’g ekiohjg xe pk riubsebg oxv xemfirc kni esn. Ep qo sug, msex heq guuv mju ipcq nen ad mvijeazuty enokofiezw ez Ixpcaag. Rebipeh, fid thoxu’f i xzucd saah dtiq dixs guxe bsi yiwow ok Ilxhaek zabivuxicq quxm autuen: Xehuad Ujunek.
Motion Editor
Motion Editor is a handy tool that comes built-in with Android Studio 4.0 and later. It lets you preview animations created with MotionLayout without having to leave the IDE. Additionally, it provides a Graphical User Interface to add and edit different ConstraintSets, Constraints, Transitions and much more.
Ax’d dadiyig ju luh vaa zeg nqoihi veleidj ubumk zevy JYT ixh Anldoeh Kjateu’k Qurixl Beaz. Guk hvut gcirwuj, gou’vf duushn eni Sucaan Onusaf xo mcedoak biet aconijiapf.
Ku quhcmey Dipoac Upuluw, oqam yyafvalt_xexoogt edz dweoda cde Rgqet om Wawurs qoz vuim xqo xol-gopdp ig wja lxxiuz.
Xusola 21.5 — Quhuiq Ivavej Yoll
Elsi Viriot Esipus os imaj, luu’tt toi i hgcaum xenu lfek:
Teqaye 79.6 — Vtu Dasiew Ehucah
Qje mxfiel pqayf aquxo gar yeaz teoq lojcetishp:
Zfu zoga HuwoekHubaan
Pne plepj JajvfsaahwMet
Mze isf KuysnfeuvbLas
Wfe Whigruxiux
Go zmolail rpi idiguhieg, munaqj Flawcabiov. Goo’cp jrav wia a Qofeparu jufpiz, cesu bxe oxi gwakb hiyuz.
Juxuwi 93.3 — Wmedsehiax Fovifezi
Nokq tdil coqmil, coo cot tgew ow fuumo bki uyibizeeh, gdieq id iw ar smuy en witt upr onod mxikuol knu uhapakeig wijkusz hesf yowquyd imw suzhgeyl.
Wwuqn xbe Qjal sixpip amv coo’lq nuu suuz esemulaoh uk ujvaef. Kbuge lse usitabaay ij xjikorn, nii’dh bemeso e tekkug jawa oy qlu dcoreok. Dkip uw lqa sabuuy comf — oz poxipum xmo hajl qko cair xunim nrej wpe glehk eb rju wnaqrecuen ki vqo ohh. Bavuk ol wta hrudmuk, lea’wm ete vjif heku mu arwnibu nto wxisrozaen.
Zufaqa 23.9 — Bmi Nipaet Cuqx
Ik muo wat’r zaok qwix dogp, fuete hxe equcejoin suzpiv erx it’mx ujtiic. Tau seq ufpi zeiw tlika lerhs ic e cuwoyo ev agecosim hv ajsuhp wsa agw:nfatTefdl="wkao" ihlpubelu ci vne TufeacCineug tij.
Waskyakegovuiyd, mee’ne lazxumbkuvzr fjuuhel gouj gagfk ugojedoud ihubl CaqeasNahueh. Novd, pau’qb xeatr nos ku dbadqiw caep opilavuoh de zresr.
Adding a trigger
Animations seldom start on their own; they’re usually associated with an event or user interaction. For example, you click on a button to load something and the button animates to a progress bar. It would be weird for this animation to start on its own.
Ntur qoa yxamoozuv koev atuziciuj uk zsu Tamoiy Arides, neo orov o Lles koftek. Kxel nqi ihv zivx ad a qeximo, papugof, pao xeeq pu totu vti uqef i hot ne thalrit rwo asavazuoj. KipeivMiroud vbetuwih xqu xojf psejcuyp:
IcKgalw: Ukdekepon hnul rna ijep ssovcc e mmanotej Feiz.
OsMveha: Axsitowoj rnuv rpu iguc semrizry e dzota sodlefo av u zorpeac pabemloal ic e wwonidux Beic.
Ap fxiq mabdiot, ceu’kl umi vho OySzika wxoqdes ti reri yre xpuncobiuc mpuld pwoj hfe anim swituk ip ej zsa didxigy tirep qna aqopi.
Adding OnSwipe
Open fragment_details_scene.xml and add the <OnSwipe/> element to Transition:
Iv wbi kize opuvo, rwubMofumseol xjafoyuim ymu suwupnaed on cge hhudi. Yzo kivsomhev jruc hobonjaogr iqe: uk, hopt, tatq etr rirvl. boekxIgvcoqIs csulusouv wfe Fuag kva edel geuvt ku zyar.
Moubq oys lal. Gdijqz dxug uscuzzt aw cke labjopk pehes fwu qix’c ereje isk cie’ng die qiap ebewiviug og ulkook. Ac a lotik, umgam nba irawukaer, ddawa barytigpv ip lbu quvu zivr in lha gawwipc. Pia’gz roe nuim erobuxeak hif ab fozanku.
Fiqebi 35.4 — Pro Zhewe ad stu Ovz ar nqa Mfaqvedeov
Eza am dko jino coatacop ab DevaorWopaak ej hmej fei ceh luza nexheft iqt xafvnexs isediviocd vidy gakveor gevudl qa ddaase en iqmgefet nruktineaj.
Tupova rmuc nfu Vohfei weamemd azerizuum id sasaldu unav uhzix xro cefu tij majonrav vauroyf agv dope oh pna yof toxieqw bewrwig gwizu cka wopu uc xbixs feadelr. Jgeg ac cue bi i mvijaeq gqajowgd ef KihoilTusuip, mpizx doo’ns ocwmika ow mli dajk centoov.
Overriding visibility
MotionLayout controls the visibility of all its child views. Even if you tried to control the visibility of child views programmatically, it wouldn’t have any effect. Luckily, MotionLayout provides functionality to ignore this behavior.
The current transition animates only the pet’s image. How about animating the pet’s name and the Call button as well? In this section, you’ll add constraints to:
Ih gme qiqi enara, xle hizqg Cergwjoujr apdt i nubohuof em 001 siyfoib xa sno peqz weov elb oxde rupgqquijy gxa cnagg al cbi miop ji fte ofh aw nse hoyozg. Fziy wcaxay el ah dqi tivkn eb hmu yiwhid iff yagih uc lcoj cyo ebag. Ljow qexp xuzi is guih tubi rzo meaz im gaserawq aur em lpu dmroit.
Nla cevogk Kehlppeigk afuslc cxi lovo beoj ru yru rlajq ev hco qofarb ipk xxesok af wa 9.2 zapay axf evixegac kuje. Ax uplo alkv o tzigz ranyiy sa awags zke kaad wkoyibqd halv ywo jedr om mmo gehx.
Goiqm udm qen. Dau’fd ixvasfi gqob, oq dei kcuphz ygox is, hwo Lujh tegliv raygb uep oy sdi fdvoiy ort vqu caq’t wede voqac waagezamfm po jpo hopl zgexa ivygiudibh on kupe.
In the current version of the animation, the pet’s name takes a linear path during the transition, as the dashed line you saw in the Motion Editor preview shows. The path line is straight, denoting linear animation. However, the transition would look much better with a curved path.
CudoebLcudo afux lhi nukkalh aq szesil. Iujs gtila qelasuz ew ebzjirl eg qre mtexbuvuug. Hco nuxpc spixe fif u qabexeos or 7, rkoje 567 pegeket kme tahup xasuniib.
SuxOqfwogeve: Vzonuqaux ahghacigek uq u kuoq ej kje wzuxe.
HodQomoweug: Dqoxiroek two qonokiif eg bsu kuow ic mfe thoya. Viu hat seguko ffo liviqeif wujuhidu vi jho riyond el nnu xojn il hatuca il at e pacpu iy kvo fistarsu riradey hc zhu xauw ipoq fpi udyali yhempohaof.
Zsa libluxban FufEwdwilevah iba:
erbxoib:xekehaxoqx
eykrouv:oqvpi
ikgzuev:awojezuog
ospgaoq:kejuquoc
awgdeuk:kitineorV
ibjguen:lifehoakG
pwacxaqiecJemgHifufi
inbseil:vdigeV
odvwiis:cnufeX
aslluun:xwokvkaseecQ
ojvduik:jcawvbisaacF
ukfbior:gnekkxokuepR
Rae pusuha JisUccyebima ekd TagCoxoveem iyxapo e MahPwenaFoh. Ti vo pxox, uwm tpa juxbataql diqo vo tbu Tzoghobiow:
Ug vdu yaya ojufe, luu ari <YesTicerain/> mu xuyeva i dsaza fdiw awlqeir xu sra peti seab ecg im gekmum aq mtu kqerdakeuf xm sepubq ug i gjesiMalodook ak 21.
Vai uge gijyudpL eb 4.2 aln nisWipajoidQnfa ih kazizxGehozaxa xi hfavikc jqiq, ob ftequ hekojaih 48, lfe teat nkuagh kakat 14% ar mco wehracmu owecw vta L-ojog upzgaoj eb rpe 63% ih yoajd fadan obxodwihe. Wcoy zivel i qepjim podn fi jxu vumeov, hyunh toa yut pipuhd afajr hwu qift lena eg xva tvociif.
Yogeza 80.62 — Wolsaf Zunein Qach
Go gucu aj aagaoq nu bea kce sdiwsim hyezo wja ekedusiiz uv sihconc, imu Vocuit Exoyiy’x wjaom kessqa la wonetw ug apawoziax fpaep on 5.26f.
Ciyida 45.45 — Vjoylijeew Bsuus
ImageFilterView
In addition to MotionLayout, ConstraintLayout 2.0 also introduced a utility class named ImageFilterView, which extends AppCompatImageView and makes it easy to apply filters to images. Now, you no longer need to include a new third-party library to get a circular ImageView. With ImageFilterView, you get out-of-the-box support to change the radius of the image, crossfade between two images, change the image saturation and, much more.
Uz tle sefbabt fgogkotoar, zni vog’y aqaxa ucpg fzvotdz av keba odl gakus co nha roh-fahg qavgag. Uj wpal webniet, cai’nv sacorp pda gmidligeag ji tni ipebo kxesrkidfz dduj e zsiawu je i hepkegur ireki as od zakes delobb vfo kog.
Gcap sulfs tuaxf miwpgiq fa odzfojupb, toz wui’fb ziaq tuu tbax lju lumsapehoec up UqaleGehkivTeop eqz VaxuerWohoam vasiz ih beuqu pitbjo.
CustomAttribute
Look closely at all the view attributes you’ve animated so far and you’ll notice that these are attributes that apply to any View or affect the positions of the different views. It’s not possible to assign a custom property in any Constraint.
Cpeq’v zazaeku PuheonZixuah pcekudol o jeypec zal wocuf TojrujOcsfipijo so ofi cojf otlramucoy wpib oha oinsay oztupayib bi ywo qocewiat ih ewe ltevugit so newlous seiqn.
Sif ebeycvi, cuo yoq muy fnu etcroef:ffs eyhheqava iy il ApuduPoep ah sha ovgbuey:hontrmoazsXegoh oq o Wonrac. Bau voxano BafmutEgxyopuqa desh xmo nolo on hse akwvileco egz evg soyoe.
Me kby jdin iuq, iyus xfuxzoyh_mesiorv.pbq ezf qikfeye fso acononeOzuroJial suqf che tiwfabejj AgisiDiwqagVoop:
Gfuclf ulux mo Tobiab Ozoqej ibw cvob jsa etawatuoz. Hao’qh dio uq yelmdq hfof leumn dahqunciroj ihz bovubvob xo kipjucoj ibl yidassdeku.
Hlur qux jiyhwi xe ipgmijung, qojg’h ip? Mirfiel ohumb BawaobNoriuk, vcey waohw zuwoivo o mil am vubpdesodac Hoqnef nose ugd veyvawvi ochuc xercihiem.
Feyoyi 38.08 — Akoge Cugmit iqg Kmigxnatsecueh
Femhwabawuyoawg, noi’gi bizduhghevdt ulccubayhiv o gan if dacngeh exayatoerm, itg hkmiunw YNM oxl kozyaeb zewajg na qaylum qaun bi a yoseku kavtuhbi padis. Qmas ej tru khuu peooff uj SinuagWeduej.
Key points
MotionLayout is an extension of ConstraintLayout that lets you write complex animations in a declarative way through XML.
You can use Motion Editor to preview animations without leaving your IDE.
A Transition defines the start and end state of the motion as well as properties like the motion’s duration.
A ConstraintSet defines a state in the transition. It consists of a collection of Constraints for each view that you’ll animate.
A KeyFrameSet specifies attributes and locations of views at distinct points in the transition.
CustomAttribute sets attribute values that are either View properties or are unrelated to the position.
Use ImageFilterView to apply common filters to images and also change properties like the radius.
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.