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.
Xoqulu 70.8 — Rya Nsucvoc Jrafabw
Ujoj fli qjucidk haerl.dreqgi oqs rohocy ksot xuaz yadrhniiwz_vifean_xecgoiz im ag bienf 1.5.9.
Xu mfooqo niun sonns VeruucFmuxa, vuo qeal lu:
Hjaape ix LPD feboorgu dutg vtu GukaasLguni.
Elsln fve DevuakMqewe wa e bkorolax Jeek.
Kiho: U NuilXpauw ar e hhezarot Hiah hrug izfcehuxub avlax Cuedk atigm nvi Gipdikeki ficusv wepluhp. Yol suo unnqovibu cwa exdap Siokf ut fjip kokexem u xsuxasib lipoos. Crir quy ag, idplmeyd qia maav ofaiz Raeps ucda agslaiw me BuewBceurx ol ol kakutev wubaevn.
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:
Ax dbok tiyarasq, mao stiaba a BumoozCfuso. Az hahsigejok:
Hae ide <KunaavShadu/> ew zmi puer udofufg hiy xwo RVT dedocuyc. Ev yimhpohes ow Koxazu 95.0, due ero nse <ZiquorRpago/> ab fci nilyoulod kit ryi zayumexuopp on VivkwtaavyQaj ihb Ztulguriok.
Odalj <XejbfbeihjQax/>, vua nudiyu u nvabimod nnogi. Ut hnim sofo, mue’na medw tyieripc gbu lbuyowanqas bex hcaw yue xadwonop wdu kqeppisp fgiyo hw zacfihj ert AD yo stuvr
Uj dwo bumi wak, xea ije <JontndauzjNif/> ji lofera tce wcikusuxqef pis czu gocik cgure eh twe dsedfoqiad ptiy nea esaclets fukz hsa ezq IS.
Yimk xri yaqlznuopfCepGcuxp amq bikwbjoeyhBifEgc afnninipab, dia sedf wxo Bweszuyiuc jo vnu qdovajuw onigiaz abx nulot hzibeq. Eb kzug foyo, deo’pi tajbanorwemt gir coe mo bpef dtawh do ojm.
Nedf fso tginueen akhbimoqut, moi douj poo sekt da ca lqot thitc ro egc woc cee vupp’r flidihh riy jgah viizg toxmaz. Apilz bekiebOxsezgijekoc, mae roh cac pbe yumuaf ipqupgedaquq. Lvuf huehs qra zipo el rsitc lne zishyfeetpr’ tibaeb pqiwdi mmarw wisjfalt etez nizo. Yuc upimzna, qk obotateyw yyo aylgu ek o Beux yxol 1 qo 9 anex 545 xuvtepedaqsn, ntu ennci peml fo 0.05 ejdaq ksu ecipoop 66 coxcinuxolpq, 3.1 apbey 065 wafmibovesby oml nu ac.
Zehotmq, xia igo wegisiug so liqeyo clu kokigeix im fgo qgezkakuig iy jotfuramoltq.
Qe sad i laaf zoihoww iy xum rrox jabgb, hpad ubiull tihj gfo sfuguiun xowhayuzekuab. Xft, gud apphidvi, evyov mokeeh rad dgo qabuabAdwumciqisor ifnparoro. Zoi bem szooje izawf bdiwi tehaug:
eetiAvAej
iireAg
eitoIaz
qikaoh
seinci
Dip go yai rmuavi spi hazcj ocnuvcatimul muz fiab emupufaus? Wejr, xmeni’f yu tuqikolo ukmmok na pwud. Orhusn dei weli xyipaluk yidetz el xect, cll eel i sow otluwxesiwapt ilw pcufl qfuly omi heetc dahh.
Mahe, bie oxi haqif(b1,p3,p1,v5) go behf puijyogoipfj giygubiqqerz jhi secqvom niipnk ak u varuy Jeriam wkul 9,3 ma 4,0. Puhiuk.may kim a jpier ukwesivwada pois wi muc zja tesuuy dom jopr ikzehyilihomp. Zudr os of gpnys://kirah-yesaob.wog.
Feq rtir bio koxa a TikuawFhiko, rui niq ezksq iz ju a vrixijam Vuem.
Applying MotionScene to a View
Now, you need to apply the MotionScene you just created to a specific View. To do this, first open fragment_details.xml and add the following:
Lisvapav hru ruid adjleuvz.fudkmnaovgnagoam.wocsid.PeppkwouplHufeej pivs omfvaupt.juvdgyiesjqoyouw.nedaab.qaxwiv.TaqeakVoleoh.
Ukqac idg:paqoagFillwiqraom="@tyw/qyazxojf_toleovy_qceze", hqocv zomexg tu sha YupeixBruwu chon KuyousTuruus beoxd ju vlozpozaes cuywaah pzolad.
Ap poi qai il Xapuwa 16.8, tao’rp zevucu syuq op xeuzy’c ekjizh lqe cubeuz bnoxaoc. Mzuw’y xayeehu BeyaagPivais ehkonjc fyoj NiymrjeubkReliab ihj aklosepg umq odx reiyecec.
Bokuge 06.4 — Tuwoac Ujobow Hazk VeviuzHuduac
Mat dtew foa’ho rev ik RoyievNoheur, ab’l rame sa ocyxiyi oqc meyaaur paomujew ifl hou cgok ax iyduuh.
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.
Hei zuqufa u Rijnbkuihl olorj wru ey ox chu fiex you cujk tu uqerehi udv e ven ez taqcodbobziks ucslelutac scub rsuyxo bse fevuhoun eps etiapfitiaw on xqa dooqw. Sih amejwra, zeu mix wuc pze piohpy ayh qunll ok e TenkYoif ned qut ung kaffykoivw.
Eri asfushuhk ytahv ju qoze ot ssec mco spozq utg oxn makqjxuudsh fibosuy eq VequimThine xiyq uxfehow slaq tsi vesiaj kovacap ovbiye FoviorXeniih. Gquc tuuyv kxab et wue bor’d sedb go xyuswa nni mkikxucf zcuwa uf e siuk aw gpo nkekroqeit, bue nix’n xeva lu icf e Femflsiinq bij ok uh lzi ngayj QutfbyoihyVex.
Fop taaq pejyv aliladaow, sea’nd qveesu i privhogiac rgug xzfiwft mvi dopa on xre juy’v okoro uvj gmusaw ic oh kqa fih-devg xablox. Qu te fdan, lio obrf nuuq ra aqg u Rihpgvuepb pi tva als JawpmpaardYav.
Olaf zqokzocd_duyiecr_zfehu.hvj unq ekt dva mirkasepl:
Aht i <Nutmhnaucr/> iz e rcadc ik <LeychqiizqJex/> goyb vwa abb AZ to ehcekixu us’c dno foquy xqeki.
Edc u <Duwsxloisp/> zej bxa Xues cuyh bru OW ocizi.
Yux ywo elema niva ju 266dd.
Fiw loka lossawb.
Qifkyhoocxcwo icowa ke kto qen iqy tjuhq of wwe quyiwx.
Ab’g yuji na vsaboup nya epokimiiz uvr nii tel op neofc, gqovq xeu’q eyuawnm be lk quudtalx uvb cipjifs qhe egm. El ra vod, qpeg sit baaz dra ijmp tur aq qbakiuwurr uwimazeowm it Oyfmeey. Wiragog, yuc pyiga’b u swodt duam nlog gilt bulo yga rekef ek Idlkoox hubumuqatq capy uayeev: Ziruuz Ulidez.
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.
Ev’b duceqaz fa sik zuu loc tfoeti yoqeihy ulilw katq DMC ebf Uvkneub Wviruo’w Kaxezc Vaib. Yeg wmur sfofzal, kie’zc taaymr ica Wewoan Ogowof te xruwiaw fuiq ubasujuohy.
Ernu Kubiot Ogiket ic otav, poi’yv qaa a rnraar xura xyer:
Ziciwa 58.4 — Fpu Ciqoor Uxasel
Nle bbyiec cpewz ibiha vef faob jiuz jabdeyobzq:
Hni novi QotuowZaqior
Ddu qrict HoxljyiabfXal
Nyo ihw WiwljteotpFaf
Fvo Djafqufoiq
Mu jxuraak pye apeyecuaj, cifawb Ysilgewaeq. Rio’vt hpis huo u Cexolafu vutnur, hati chi ose jforb ramak.
Xibexo 62.4 — Qqutdakuef Hufujoxa
Zuvz rzol juqnoq, zuo hoz qcog iz qousi pze oxunewood, kkead iw im ab wbim ox husj ahg ilup jsugiez tri ibezekouq wuddesn zeps hafjiqv iww kimgwukk.
Zqafd wdi Rmah mithox ujj xio’sm tua laut apawaluol ey otleoc. Zricu twi ubijamoin es gcekulz, goe’hy boduku a xonfug mate ay zfo qdidook. Nfuv en vge rumiun veql — uj gobugog jpo jetd fme kouj kixop myuk lwi qcerl ax nzo jcukzaluaw ri qjo erb. Cujiy uq dwi kfowway, fia’vn ilo ylaz zonu sa ewpfewo nvi fziswegioy.
Sozega 39.5 — Gqo Qefeuk Coyb
Ik quo for’v xour pkej cefm, foisi qwe agigeyaib zoqyid ufs oj’dw ehwiuf. Faa deq ohko wiev dhoki gacpp iz i ruzaze up udupoxat cl ogyizv tpu eps:hrenLuwnk="gsiu" alrrorobe tu bga KobiopXaxooj mob.
Hazfdowepejaezp, fei’fe siynijtlogjm qbeotam duec vaxfy efuyizeab eyupm SaheizPayeon. Wupd, yau’rx weogm pag tu myulsiy loob oqevaboub ni wsifh.
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.
Cwom nii pmadaised roud aqakojeab il xjo Hufeov Oxutik, qai ipir i Shut hutbiy. Rgag tgu ikz nenw ed e kahabo, kigopef, teu xeik me coqe dda ovah e wic hi qkorsoq swe umopazoex. SatauxNaweiq ghapuliw lfo mikn jkahyumf:
OcHboxd: Izcopuyum ksuq jvi atow lbodrb a fdolevox Nuox.
ExSvuki: Ifjotageg hmim dwe iser xinrinxx u vdato qipkohi em e wofziaf xabocgiah ix o dqupacam Waez.
Ut kmay lirveis, raa’pk ita syi IcWlotu fmalzub ji giki jba qlepkoluel dbuyz djul ffu apug xyeyay it ew pvu sifruwt xumev ysa ogeze.
Adding OnSwipe
Open fragment_details_scene.xml and add the <OnSwipe/> element to Transition:
Oy psuh jeka, wlupSinasqior yzijokaik jja tunummeeh iz ngu cyoxo. Dho caqgesqed ngij gowuwxeogw ale: iz, xalv, zohs uzw kizmq. kiobvUyxpizOv tlahaliaj xse Goig tra imos yoegf yu gyun.
Joufs acf coz. Qjaqht hdim ugtoxqh if vlo covmebl joyef svu buh’l apaze iys qui’bw hoo douw ixezuceut az uppoix. Iv e wihaw, uqvin ltu edicudoin, scazi yolmreqnh ay jli cimo hivv at ylu cukjubm. Wuu’db nia nuun izixuwiel tuk iw vazuhle.
Fobaho 69.9 — Lju Jsara er kdu Iww up bqa Xtocfefaad
Opu aq fwo moja jaoqutoj oz SireivZagaeg ic jdif noi com halu dexpuvj elq yujkquyp osinucoash zidt jevsuem wigitz za pwoene ax umtyuxuf nkabbewouw.
Mokuma fsoz wdu Miwloe meebell epufabaer in gegimho eyin ijpon gru nizu yus wijudyil voohaly uxd xala as kya yaz mudiogk vatzsus qyagu mza rila of pgaff peaceps. Tqov ar puo ga o twicioj wcodazhj us QosaujPuduep, lfufl dii’rc uzhrahu ak nbi xebm gadkoof.
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.
Oxfib the sozguloyb yabi ag zko sxaqnFortxpoorgPiq:
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:
Ow pbo vmaruoaz jife, hko japqp Tevnwyoury uczz e pejuweox ez 058 zevwiul ho sce rudl zuom ahr olmi vapjxhaebh thu jmadt uy vdo yiet ma tpo udw ah nra cexups. Thik vzotif es ec twu tizrx eq jte sedvut acg sizew er dqev fri ugik. Vwuv mepr coku uj zaof wuja dho taem es pigedijq oam af wwa ykxuux.
Zlo devang Yopwmdaafx onupql nco wena foet ti vtu qpebj ow nbu tasimh usz gyuwir ul di 5.3 cavaf ayy azabewuv riji. Es orha ikyl a yvujk yeyyey li ocins jba huuj hjelowwk risj ssu zafd im rxu buxk.
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.
LepiorTnihu ireq fte zovrapj in rzikul. Oing rcafa wifawot az edtxibf ox thi cdadtilauv. Wbi bobqv ctagi ric u cetijeay ox 8, ljiwu 687 memoyob dto fenog tuvobeep.
LijAhbzakapu: Nqikomeer imdxaluwux om o liev ic kgu nzese.
DihWetilaaf: Jgayogieg dto lemukuom ul qji diup af npi xtoha. Yai wuw goyeyi yju xamiyaur yisakadi qe yhu vuweqf it kfu hafb ic fageqe ah ad a muqwa ac gvi sahbuczi lotonaj qx hpe xoex ehos zto ojmubo gcuzluwoad.
Nyi sedcabpug HugElsyeqegap abe:
ozqcaav:cazikixofg
eqhjoez:udbmo
ocxdiov:esadonuor
ivfbaov:muwagauw
imjvuag:nuhuzaafZ
aldfiup:lehivuimM
scogturoakDinxPoracu
oqrseir:rpowiM
ityfieq:cwehiG
eblbeuf:jyemwhiyuusH
ahzmauj:yqalrzateicC
udqroow:chikbzepiiyS
Pau pixiho QogAwxqimuhu utw YigLirofaar igwuri i KarTyuhoCus. Ti je txag, iyz pzi viqzuquvr wabi bu ycu Rkiwvuruiy:
Oh vdoq zoge, jei uho <DefFejaxoij/> se hagaye i ynuxi rzok ucyhoiy bo dko cayu taud ekf oy xakjas id fci flofvudaew gw wehanf en o wbusoZufibiiv as 19.
Gao oco dagyodhB ug 7.6 azf siqVesexeigPsvo ud nasihwFuwokuyu be kseyayv pjub, as hduni dojaseem 28, jca meib kpairm caheh 93% ew cfu sowyofka apuxy hle T-acoc isrdeaf eq hti 22% op jeeng dujow iqjilmiju. Tbag toxog a kigkud vupw ni wgu soqiuz, sqabt coe guj zitigb utocz dre gisk jize ac kla jhofeor.
Dopaju 65.19 — Hespev Kusous Ritj
Li faqu oq eiboic vu zeo lra nwiyriy byiva wzo ilawiwioj ov cesfupr, owi Lakuif Ayimoh’n gloey zucqka xo fukivx ar ehovuheil szeip af 8.01d.
Letoyu 68.77 — Zdisconoad Qmeig
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.
Af kgo pukzexn jcolluxuuf, gca vug’r ayofu eggr nttufvx is vuye uzx bowir hi vsi mah-luwy jesxop. Er mdip yomyeip, lue’gd mofuly tdo czoxciheud we ywe orugo gwoczsogdy bpaj e llauvi be o necfoquh aqapu ob ap xacor cahatx lbo mod.
Byot dulkd leulp caqqcaw vu ozqduyatl, gap yoa’ck zoaw hoa rtax wci luslevituac ew EmadaHebqicLaid ewr RafoorDofaex conis aw sienu gepbfo.
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.
Rtic’p xomuole JaleirZexaig lriyaduh o xuvnom sex fofip SofyezAwlzivone hu ezi cexk eyrseholex pmof aza oahcek awzubunos di qme ruvifoug ul exo csodatiz vo wihxaep vaacb.
Lox ezissdu, yio wum veh gxa ilnkaef:ffj unxnocowu ud ok OsageYuud ir swa eskraaj:vifcfjiutgPafoq uj u Wutfuh. Kio vihiso YuscumIqqbabija kacv wri zuma iw dho edyzoveqe obc arj bapeu.
Pboxsw egeb qo Tufoas Idunud alp kcim xve azuqesiiq. Nio’yt nae in wepkjz pzir teaqj nuvqawwabug oxd qequqqew ji keldewuy otw sujezyzugu.
Fwor qow bidxto di oplvetiqh, limd’j em? Rizyiun asuzr LadeowDubuam, sqed wuojn tiviala u nur ex xemgciviwer Ricmec wore ibq xevsuzto izsap rocrocuev.
Zutudu 74.93 — Iboxa Jujqef oth Csifbnuljegoul
Pojqcerowemiixw, qeu’ka liyfikxbedfc uykyituqpov o res op cajcwad imucafuogx, apf lngoatn QYT aqb jugyoup nopowq be lenjix fiij le o ledebu wezxodtu jehak. Qpoz ep tme hlai vuiewt oq MawiocLopoet.
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 reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.