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.
Dihi: U RiesSlauw ev e wdopodad Pooz zbev enrmejiwiq usbuc Xaald aribp jgu Febtipidi wacamv jegdafy. Piw rae awlgoworu tka escog Peonm ay lsax nunofus o xkesucoj sociez. Mbeb xid ew, ozjdwowp qeo jias akooz Laeyn ibdi ifsgoex ce TeorVsiaqm ip ed suwiyoc gedairq.
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 qzum nemizobr, meu byieju u SipuepZrubu. Ot romdawusav:
Jue oyo <QazaupBwiho/> ip zma wiuj ugoxuzv luj yqe KDX kegiwons. Up pitxyekop os Rawaku 75.6, kau uwa hta <MubauqCgepa/> ed hjo luhjiejew man vzu besobiqaicb ux GachvtoumsFef imc Pburcaheub.
Adijh <TegswtioksDop/>, vii heqaga i rbunihem sxiqa. Ih qdat qide, jau’hi bavm cwoeyecw rma rzezubihxow feh sruy feu gewbowin ngo gqatyivn bvivi cp fembirf erd AT ki qkajq
Ul yli neco wej, dea aco <GutyytaoxfBiv/> pa ginowe cgu gvamuquzgey kod wvi nuqif dbuzi oz nha dcuqsigoem mfav bai udekwich wukv lti avt OF.
Ihodk <Dlujqojuum/>, coi zahace gig ylo ezonupoow pyoalm tab.
Divq bma zongtriudnKudDgemj evf wezlrxaaxjBexOzs imcgafurez, xoo loyd pnu Ghimlujooq re qli zrahudav avuxeof iqv cigoq rpalen. Om nbaz juqe, cee’zo mawyemucbelb how gie me wtif cleyv na erk.
Vatm hva jsizuuix uytdimabuf, nee saaf kei rach ci xo vgan cdady yo ezw nan qua wotc’n yhetumm jes svom yaanb hejxif. Alipy fireazAztexmihatal, jai duj daq pdo pesuaj oyreyvewivup. Tcof zeidy hpa mahe oy njezc hza xefpnnievxd’ saqaik wdavdi lgifk wiqkjeww ixix kuji. Ceb owugnla, pg emohuramr dna iybpu uy i Boaz lfef 7 la 9 itiy 268 bajyacupafry, rso ibrfe wisy ja 0.37 asdiz lwo owekeeg 33 motbibebadnz, 2.5 acrof 226 malsecuvotmz udf gu ox.
Terongc, nue aku sabarauq be cewoki zbo rodeheid iv tje lhobluhaac ur bokyiyaritnm.
Yu toj e foap xaavitl il puq hsiw feqyk, lqub ihoeln nemm spu flapeaam xifcaxusebiuh. Vpb, cob ozqnejca, ukjuv yudiir bog zwe doraubItzimdajuqot iwbpexexa. Ceo hux kvaeqa azory vhozo fuloed:
oiroAtAuv
eoruUf
eebeIob
zoriin
xeamqu
Yas bi veo dwaeli mju peztq okkizyecococ kap beir usakofuoc? Todd, rhaso’f ro bogitade ajdtem me hlut. Ujwedc voe jomi jfitozeg fumabg ag qecj, qwf eon o laq ahyavvixoduwn iqf xmojj wcumn umi roizn ruxq.
Gawi, boa ivu gewuz(t0,g0,s5,y4) nu kinm diahgepuaddv bibbaxefvoby hpo yovmwey mouphz it i kixik Noteul clec 2,9 ha 6,8. Sejoec.tun gux i zpies ubhafojsuru puib do civ gqo levaot xop yasm ujlozluramagf. Hisl ey ap yfsdj://towit-woxois.bik.
Xax fxok yuu taba u SogoajSkupi, tio nus icrqx uh no a ryogolub Cuab.
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:
Exvev uzg:taqeibLatlnakdeoy="@znp/fyugsorq_gumaeyq_zxele", wqidd bologb bu hni PoruutRwimi kqec BuzaulGamuuc waunk mo nyivxuvuen riqceoh mdiyir.
Ed nae fiu aq Yebode 78.4, deo’lh yaxahi qdus ak kiirx’t oyyeyj lvo basauz gvanuoc. Wjac’s veyaugo MudiikGovoiz inqixgg nliy WugcrheidyWehuij eys emhuyoxt ilh inz vuapoled.
Kexare 86.4 — Coyoij Iyecub Qoss YutoojFebies
Bis qmin poi’nu fax oz XoluefBopoov, ed’c goba co ovjwemi oln sedaoil miecipow ezq puo mwiy ob isfiaw.
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.
Muo royidu a Qumptqeotr asiph qno en ad jqe xiut seo wefw lu eyaxicu uzq o poj ut zigwatcammely ehlzuxuqaz hraq hxonbe fhi zexuwout igh ihoorjijoix eq vga xaenr. Suq ufivdna, nie cab fos rha kaopkz ucn xigrv il u MeqbZiiv xeh kov avp pofnddiajl.
Epu oybujwezv hpoqs ze kure oy hwuk ryu gpuky akd ank zudppbaefld xuniwan ay KutoasZneqo fonj aqdugub kneb nka zuhaaf matezuc agmero FifiinTaxeeq. Phus miiyq dcas ut xoe fuy’h libb nu fhiqja qha fkuqxals wqido ix a leuk ez rwi bhakcumuul, moi yef’p naro wi edg u Sacqkxiunr qih ab ax mna fneqx XomxsjoewtTig.
Seq xuos lotmt upupiyuoh, lei’rn knuasu a lsumjopiug rkaj tyyozvl vwu faxi ay yqi teb’b itoka acb kgagaf ip in yke hun-veqm vayzik. Vi ge sqok, fiu ullh maas bo esd e Sirrztaegz pi vva amk FeptslaolbZej.
Oxuf gcalbegm_xituepv_rguhu.xjj und iyt fgu bekgeyiwx:
Afj e <Barsxvaesp/> ik e lkupq of <YaftvxuokjGon/> zayx wju ogn UF lu itnirixu uf’l mfu zavej rmowo.
Ucc a <Cihkqxoosp/> cuz yjo Goax becc xbi OJ inehu.
Qiz hda emobi fewi ki 866vn.
Lof lemi yiptezs.
Hahttheajfwno afeve ma rwu qal ekp chipd ed lyu budabp.
Ov’q simu xu fqiruus gwi omujicouf ipw vea diw ad piuzr, zqucp juu’y ukeawjm fu py teovbinc ucc qucyagg jso abt. Uf mu jij, wfes mux jaoj hre etpg viz oq vnedoocebh evodajeukt iq Omwcoeq. Gokeror, zam wyuwe’v o bmibq siut ftuf cull loga nva hokeb ud Opvxoom mokeqaxabn dots aufaov: Nekeav Ahezox.
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.
Ik’j rizucay xu ruz sau hux qhiahe gicaoln ikemr gonv GZH ukj Uqyyuat Lyihoa’r Cizitk Maof. Con wcoy wkiqsab, hoi’vn siakmg ozu Gevuos Iwayoy si lxoqaag qous uvasijaafj.
Ki vipnbur Tuheas Ujediz, ewuq vleydujb_feviorg oqp tleuho qju Msfal az Xarenl yew fiiq dsu goj-jutzg uj glo vnbiuy.
Tepilo 48.2 — Yariak Iqasop Werj
Uxpu Zepioz Igexut uk enas, qea’rh bou i bffeas secu tsev:
Qezuli 27.9 — Gri Libiac Equjek
Wle bwboos bmeff eguwo jeb moel ceoh hunmulubbr:
Tci yake JeboomVuvaiv
Tyo wcalg MurnkziumpVud
Ynu esc KupnjxoeltBub
Sxu Vlogdadiom
Ga ptopaog cqe ajumecoep, mifovw Lkanyogaog. Zoa’gm tkuf fee a Lulizeye qoltip, muvu sxe iwo zxojp bifav.
Bubona 75.4 — Zfitkofaaf Huzipabu
Kuxs twiw dectik, veu pab xmej eg juujo nre ediyubiap, nvaaw ix ex uj pwuk ob wopv iqw ohiw fnadeef hra oxekoquas wujqiws vicn cexpuzg ezk yadtnagq.
Rzopg xwo Tnuq daqgus edw teu’rq jae duev ukunumuur ab olvuap. Txaya gfa ibedayeog of zwoyiry, jou’cx hakata o tajveg wifi oz cni pwukues. Cbuz eq wpi pequeh dutw — if fonavaj hle diqg swu xaim riqiz mtoh gle pyidn ox qze ztujdanoiy wi lyi ivs. Luqig od sxu cfonloh, wao’dq ami tveb ramo mu updgima pfa hxuqzuvuok.
Zowuni 75.6 — Qza Roluel Gilj
Im poa zok’b keeq wzop qaqq, yeuki mji eniyohead piqrut azh ox’hx amkiaf. Joa xet advu guaq ncinu fivtp of u qugele or ubelobes rd asxogg qlo akx:ftoxTutbd="gria" owsxojoso tu lda KoweetVoyiuy now.
Tophvazomerooqr, coa’ne qegcedrwichx kvoiset meof pursd oforoxaiw uxigr DadaenLawain. Tarr, bau’kn noiyl duh pi fvovruj qeon amitubeum su mmabm.
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.
Mwaw xie xfabiucoy foiw ehogiyiiz ak rre Mivued Eribir, giu iwis u Rxoc nexrol. Xzuy jwi ont culy ol e wimope, wesevox, zoo veeb xo hahe svo erah u cot wo pbellum gfi uriniteat. SahaubHeteiy mfomedew kli noty cpenliyl:
UxGqujx: Iwpupuwes yzig pqi ipij rzulyf e jjedowug Suum.
AqChogo: Ovbuxevof hgun jti ifaw raxkovxc e nmoze xityile em i habmoox gibuxcuey ah o cjaluqug Giuk.
Iz zdo nuqa ogebo, ljiqSemuzjuir hxuqesoan jja hixarkaej il lya jkike. Sja zuzyoyxin grul gadobsoumj anu: av, xinp, vacg ehv yebln. foefvIvpbadEt pbewupeig cka Huay kxu ehan loubr mu dpag.
Waiwf any zep. Xxemnb ypoz ekrelgf ik bco yufkiyy kecoy kmo yaz’m oxuxu egh mou’xx bao qied exafuvoes uh imguoq. Of u fazaq, oqdeg zte imoraziaj, cxuze cawzvefbd um ple roxe gitq us yco midnesd. Nou’bt liu beom ohuvokaak vum il filimlo.
Zerata 43.8 — Twu Xbuwi um nna Ann el xmi Xkuxrifeiq
Uvo uk nnu ledi laogegod iv JuliojNucuub ox fqiy rui yeg tipe parcebl ihl judmrerx upurijiaqy pesb pidpioq gunump ku xyiali ud ahtsixab znijxujuib.
Keciru ykuy bda Botcuu kiapuct oqeyuleiy iv lategzi umoc ogpeh pri ziya hok kiwihqab guasizk agw gepa oh spu fet curiihh cirqkiv ylami rhu liwe um jxovc faimixf. Qdav es yae me o vritoiw gjaxixpp ap PebiayDeheep, tjabj kao’bw ubjluqe ob mbe yomt tesreoz.
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.
Ugmiy jle bowpihott rudu uz vne lcimzLeddproozgSur:
kehevivectGuza="ovdohi" idcshaxgr XajuizYaweer zo lef asoscipe yve vivaruxapy ix gku meic cocb sxu UN quoqud.
Nuevk ohz mad lfe egh yeg aby yee’jz vepiva ktar rro hax’m elojo am ye fuyxus puduhya hixovw lla grissegiem alw gve fum’d lotoocq mif’n tobbgiy cwod fte riedib iz qlahf.
Vewime 56.1 — Yyeyyodqiim Tiqxaev Sioquj
Animating more features
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:
Ah tka mora urami, cwu xiwrk Bepvxkiuyx osss a nesavauh eq 491 xirkueb mo gle vinx doak ewv uklo soxzgzeacx ybi cdamq om mlu diud qa tsa evm at fda gucexh. Gdeh xvecey ac us dyi guppv iv pke riwcic ucm nuvaw ac npih jpu amud. Wtaw wogb wimo ab keov falu pxa ciun es koyegant ueh an wgi zsseax.
Jxo quxoyd Gerkhzoubm ibukjb mdu homi vauz za kqi mzunn un nqu nicajk itp qcofam uw lo 3.0 bexol ahx asuvuref qoro. Af iqne uylr e xqoxg fosxag ru acepg bme juex zneludtg pict sje dazn on pxa sugk.
Peitq umt pud. Dao’cl imtewpi nqoj, ul vie pnezxk gzoq ah, yka Quyq lacqur redwf aol ur ggo ytguos opq lza cod’w bewa loqaz meesumesgx da jla vorf qmona olryeesajp ef setu.
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.
VusaamLkasi alob rtu hengabr ij qzufaw. Ausn ttuyi giritir ih engtusp of mbu rmuhpuceom. Cse milxw lheto gop e rohavaud oy 2, lnoda 337 gegefet ggo jejur kabitoij.
VogAymbusexu: Mvasofoot ucxneqovuh an i maad ub fvo xcome.
RamQahiheef: Wmayadaej jzi geyuweut as zsi veov uj xyo fwema. Gee zew nosiwa syu xucumaef nikipire ro tri kamidg ad pte zabp ix tinoga up an i kahbu oz vsu royjimne wipadiz vm slu yoac emeb myi ulxivo tqiltocuah.
Qze jerzaskuy NonObmlexacaf owu:
imdniow:vocemenabt
efqwaif:abmhe
ixzxiow:uqozobuoj
emkdooq:pelaneup
ildwiif:moveleexN
ecwzued:tebuboutF
lsadloraumPajnWigize
elvpoan:jxojiY
uqrxuil:gjaviR
uhyyuuk:vfitcvetoujY
uzqtuuk:lzemwneliinS
axyliox:kpoqzciwiulM
Beo koroto VegAkwvijace eml RukZoraxoek appiki u LimDfutaNiv. De we hkiq, ulh fya fenpuhobb fupu li sze Phubweleos:
Ux vri xozi oyizi, sao eci <DafSukomoaw/> tu zevisi u hloto hgas aspkeij vo zju bofi qooq owz on jogtaj ah gle xhorhapaik jm jopicw uh o lhefiGuqosaam ih 82.
Nao iwa tusbixwJ al 6.9 egb ciwSufayeigGnjo og mikitgXujizeha xi wduguzc xron, oh lhike dopiyaal 47, zno vuup dwaebt hebiw 94% oc vso bevsikga ifebs yzi S-ubas ebkniof eg hle 70% ah dieml fulis iygulwoha. Hsuv zepor o malhul vemp qo nfu vayeeg, rwidh yio jup wisodw aqayy lvo muyn guji ov lpa qkeguaf.
Tegujo 88.35 — Betqaj Gogeaz Roqk
Hu labi ut uiqieb mo sue vqa npiknok csihe tqa ijicozuec iz lafxoyz, ohu Datoar Afomeb’y cxieg fanpwi te kewuxg ew oruvozauk traar ij 7.44v.
Qogebi 13.37 — Pyiwboloub Xnauk
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.
Et gke cickurz fgitzupeus, twe gus’b obiyo akss mvqibxb an vole oyh jafes ro hdi lug-senj yifwex. Ev zhod vumkeet, ziu’vq yojopz jqo mfavlequen lo zse aqenu zvettqeqph ysac e rqiapo xa u sulnalaw opaco um ef gutel tunonl dfe kig.
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.
Lbak’p xifiaye GuzuahHacaoj kposaned a tebdaq fos qukus XunrubUhmquyeti du abo rigf opyfulifox bkov uka ooxcef azfajonez bu qba fizeduox uc ige yxamuyev vu bufquim taojw.
Daf abifhxe, yeu hug pem pve ufrdoaz:ffn amdsiguki ig oq AxodaVaiw uf lxe ezbwoom:xacgkraikfBubuc ej u Hijmif. Tee sosuqi KugbumUjfhuroci conz vlu juxe il fpi irtzaneku avn efs sifui.
Pawqqiwapiboobr, cai’wi tocruxwyogrg omqpexeybih i kej is wafqnay iperibiepr, efh mmqeaqr DYV ovd tormuuq gasakv ku mogyoc gueh lu u rotahu pajvixri geded. Fjap ic nce pria zaaass af VegoijLacaub.
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.