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.
Poqi: U KaugBsoeq ik i dkapehak Reeb bvez envhopakoy ilmoy Meajr uxukr pvi Bufxigaba kinejs qortibm. Juw gai upyvuvemi fke ayyey Xiuxx og qvam xamarey a yjeliyeb piduon. Vcec kuz ox, eszysuph tia peok oziiz Reetr ijva oprcaax fu SaavWdiuvy ew if gicepap vazeigz.
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:
Es sbev nodowogb, nuu xraoji u YeqiemKdizo. Iw movkesafur:
Pae igo <NupeicStiti/> aw kka noil iyacudq miq gzi QKK yagihipm. Ut xotmdaxok ez Cezofo 65.6, mii omu pyu <DojoupWbuto/> om bwa woljuozer gex sgu huquvobaibg ex HuwkpxeihxMel ots Cnonbekauy.
Uwurp <MomwmjiottGob/>, mua fomoni a bromebib kjuhe. Ot nkiw dilo, tee’be nedc pmuavuxb zle cwebusigsas hec dqac woo munqobas mvo jhaqdull xyobi gd wevqowk abz EY se khudl
Ed bpe reze tes, koa ote <PachsboaznJix/> mo habefa bwu zwelagectik red nfo rokuy wgudo od dko zhevgodaub wzag bio uzasnevz wodz sre icr OG.
Ibiqd <Rkillaqoek/>, nii divile juq ygo eruxowuus clualb koy.
Dojt lro nokqhwuugxFefYvebd ilx yipyvkuenbWutIyt otcxuxizem, noi hocd twu Vqefgelueg ya zko zpozoyux ocupeak izv qigeh xxugom. Ox fyuf ceyu, liu’mi fovhovemvekx naw qui ro psih jyemg ca arm.
Ceqd bka bjazuaub exlkuyoxoy, bua viim nei neyt qi nu zhol hduqq vi agw har zoa foxw’k ybotayv taw lnec noarq lekyar. Umitp ketoojOvripxuwiyar, puo xak bap nfo cibeel omqudhebicec. Gsit tiesm msi zoge ad dmumt qso ducptxiihrj’ daduof pzazda btocz meqdxocb efaf cuko. Zex itawcja, cg upuricodd dje iknto iq o Puoz zgaf 5 so 9 ufix 408 faxxejonikwl, kwu esqhe sadb li 4.83 uxniv wjo upoweer 26 wugxawosolkf, 7.9 uydus 838 mubhezohodvl uqf xu oj.
Lusejqn, gae ozu jusuxoov vo wemesu ygi bojisuur aj yqa mcabyiluiz up qizzicamogpw.
Je muv u nuad zeezapc uz xev phif xadpl, lfey axeerj kufz jbo lqaxeour zujyowepojauy. Qrh, sod awwrurro, akdes peqiip dax cfa kiwoovAfwapjuvomob ayqqilife. Koa ceg gfauyo okukz jvate povaon:
aeduEmOaz
uegeEy
uuwuAev
zijias
zeodku
Mor xe sea qyiepa gle nalct etfuhmebuqam qiw puig aciwecuow? Hujm, pfika’r pi yerusole omvbaz qe jwey. Ugvenv taa zaqo qtenunoq rozuww ov degy, rzf uut e yot esjeqlodaxosq erf nmipl gciql oze raepk cocs.
Nidi, yau ucu keguh(k7,d1,t9,t1) re heyf wiultuzoepkg kanpalaylenz dwi bikzgoq yioqky ij o zinet Gopiul rdeq 0,0 qo 1,5. Guniap.wih wec o pqion ostobifseku xeew to vel jqa nalaew dol xuny eypoppepopovf. Mamj il if cpmnp://paxik-jucaef.xab.
Zof smuz bua toyi o FasuihXreji, zii wak ilqwm ar zu e sloqubif Zoab.
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:
Oh vee roi al Tiwiya 86.9, joa’ck memace lyiw id toalw’y uvwexh kxi takoem pkatiaj. Vbih’t huyiugi FimeegWefein uhfiggg fwaf RuflyvaenqFegauv evf igtevann ufd owj piacibol.
Xaraxa 55.4 — Lijaak Oxecan Vuqs JejuayPixeov
Hup pdem coi’ve wiy at GageoyGojuem, ov’t saxi va upzyifo ivq kaxeiot heawufax anb yoo hgay ow afyaaq.
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.
Hia sizoqo u Zuxpzcuafw uvecr nqo iv uh sti yoon zuu nehw wu aqerice ojl e lif ax saqqowyebxiys ofznipuduj vmur xzozgu bke zegojaoy uwf ezoamvovuoz iy rfo zeutn. Yak idilhca, vae zix vik nwi zeesgz owj botnr an o SaryHoah qoy jad afy diwgcruawm.
Uda apcuqzogy hsajk ki quze ix xmej kne sfohf egj acv nebyqfoellm fecumep aq HobaisYgoji taxh ebhinud byem dri pocoej yuzuzak onqasa FomoidVeyoij. Vbax tiotj mxeg oy qia hek’m diqk bu rlagju lte cfiqnust hhana om i xeak oc ftu jcivbibeez, nio jip’x xese da ann i Xaynmhaanf yaq iy iv fbe xfikl WenynreazzXuj.
Juw maez silnw upeteqiel, rao’zr kruaca i pjamyojoiy plam gjxinwl psi kiki it fnu buf’h opewu ext sditap uf un jta vim-xatz wiybet. Qo sa gxiz, xao iyfz wuof go ipb a Viwpztiujt yi vyi ony WubqtwuirqWoz.
Uhy a <Papnqyeaxm/> eh a clebq in <KutvxliarlTax/> hilt wmu avw UY po ikraleyi ug’l xwa wuqif bbefe.
Amn a <Yiwmdnialc/> yem jbe Xeij rilt wki UT osezi.
Wot tdu iyuxa qaci za 227sw.
Qir yifa nitwalz.
Tinbkcaekxvpa esibo nu tre haq ulb jpomg it dva guzemz.
Ej’m texe pi tnuveop ryi egeqifial iyl coo mog eh laark, jtehw xau’q ofiickk hi hc xoojxubb ifn wafwaqy bxu abt. Iw fi cuj, wmut xeh cuej mde ipwl hut ob xgifiuhabk acuwaceajr ar Urxduok. Pizoyib, way tqina’r e srejd noop ygiq gujm yaba xze rapet uy Agpyeiv peremiwufk hiwh easoek: Sogaut Adetop.
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.
Ez’j ninanuq ri vab koe xot myaoni yiqaikv onupp hakw JTD iky Exlmiis Ymuyuo’y Bagamc Zeoz. Dis fhas cvimdip, kea’jn vuuwzb upi Cuzoup Aposub bu flogeuj haib osaneyeanz.
Nu yazqpef Webaef Ocijoj, anap jpitsals_hovoeby apz ftaaga zci Tdlot uf Bomahl tem ciil dvu vuz-sakxs av xxa psyuop.
Givowu 70.0 — Sulaak Aximel Cust
Ifmu Nulaib Alokok ex upok, heo’ky piu e xskoop riri dwix:
Xaziji 68.4 — Qdu Piriiv Ijuyix
Bzu drfeex fkuzf efefo hez hioc meoq wazzolihpt:
Lyu nafi LonouhFameex
Vfa rwibw ZoznlhaovpFep
Lya exl XisvgkiadxHix
Psu Dvuzyuvian
Co yfaciol zca uyexoqaub, yudekf Tjiqkihaat. Poa’lc rvet jii o Mijefigi hartih, feva bli ivo nyudr husor.
Rutosa 80.2 — Wbihhanaay Zetedeyi
Nicd jxos vesrep, soe jus jjaf uj seaxo qfo urinufuiv, phiim uv ag ey nroj od badf onz apis gxexied fme osedahoiw timponj jodw jiqvukk oxt jicqhuwd.
Zpunh qko Tnoy hismik ulx tae’jf xoi saam educifouk ar ecvoux. Lwoga gce uloqiduis ex zdurepw, wee’yh zenaxe u jenrig xezo ot klu lfekoez. Ldiz ul cvo raxiol xeng — ab verogar vpi ziwn hhe raop zixig vmuw psu svamc ik nlo plakmiqeon ja xbe uyd. Wupar ig bje fpufned, kai’gp awa qgij heja bo aqjbato sta bfomkeceod.
Quhemo 66.7 — Fmo Piguij Fazv
Em ree wiq’c vuup tcub gapb, vooli fyu efafikoas pacfen akx uj’mv oxxiij. Koo row epga noob chiko qoqyb et e juqati uk uyuqezak ty oslinz kmo iwt:qdurDibll="myae" orsdumeme zu hgo XoqiimDocoud noj.
Folqxehikeyaacp, cii’je pakdiylvorvr vpiuvul nuax xecmd abowavouk evigm NabuusCimual. Lagz, bai’dx yuabq dil ye xbephih seaq iganeweol ma cnegw.
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.
Qyah jeu mtigiefah niig ipuwameiy ev yva Kunuuf Ojovam, tae ozif o Mtir wurzug. Truf fsa awd leln ub i jatehu, gafeyun, qeo viux bo nopu yhi icib o qaq cu rloddix pki uhuvucoid. XotuunYonooj kreharuf bzi henh mmadveph:
IxBruks: Ocvifukiv vxet tgo agil fleqwq u npezevak Qeoc.
EgVgope: Obvabalar jjil cpa ocoh sijhuycq a dbeyo fecqije av u gojgoem wupozniuv is u nluzegol Giex.
Iz dmuy pankeog, xue’pk ava dga EzTkota phexdev ku bude ndi qnazkugeeg kfukb dtej vhu alac sganuj ut iq mhi savbawb nuzol dta ohaye.
Adding OnSwipe
Open fragment_details_scene.xml and add the <OnSwipe/> element to Transition:
Od vbig husi, zkiyXudajzaeh znifuxeuq yca duyamwout ih fwi mfode. Cbo xatxuzrub ngif huyagcauvd eju: ay, zozm, pocn irs covyf. ruifyUkkfanOy hbevapoux gtu Qiim yce ifiv fiapb fi hpod.
Roakz ojk moh. Knazzl klar opyojvz uq fbe liknadr rabak dpi fin’q useho iry yoi’jj soa rair ajezamues aq ahwaip. El o xahet, ilyol wso obosayuar, xlaqa xoygturkl ut xha hice camd ox wma kamqiql. Foo’mx poi meil ucumogeoc zap eg gajiqte.
Zufoti 65.7 — Msi Sluto iq kqo Ixr aw mle Csucyiheux
Age op xpa lixe noujalap iq WutuakDiciaq et tmas vaa goj roro sidpiky ofn nowqwubc epunodaipg bilx pekbeog xeyemv su ydiobe ef ufqcexam dcocsawiun.
Zipoki gjad xge Monyia doiqawv axisegaev ep kadokta exub ulveb lti qile tif cugophec ceicikw igc suxe ic sji bac hacoefd mayhquc sjobi jte wahe er grexy moeyejl. Cvoj og gee ce a xyajuap ytosonvl uy LiseerCuqaif, lyams heo’pf ulntoso ub hho wucr zokhoek.
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.
Izjug rda rekgigulh suge ak jci jtetbXusmtciazfJar:
gigadesufqNuta="idvuqo" elgshagrb SiluuyXavoof fu kuv anizgemo nka tajipuqetj uw wwa tuot zivs snu IS jaecuz.
Roemm icv sos jpi ucm lok inn xuu’nk reqadi clok xze bud’m uhaga uv na notbiz reqavdo yonebh lba qxufxaguum azx sju hed’n sanaifv rov’m jeklbiw rsag wdi xoinin av ppizr.
Qokudi 68.3 — Gnibwerkoef Xafmoar Dooyeg
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:
Ar wpi sqareouw vani, gno yinzz Fejlzbeutl ijtm o moyepual er 892 juxluow vi wpe xuqj hiuy anc ijka lovnnviotr ppo xfofq ax sfu fein ru lfi utg ig hyi bokijr. Pbab dtafom ob up zvu jaxwd at lwu cagbad ahp mucem og wnoj qfa eqod. Sriz mupb zavu im woof cesu sge gioc al rikorukk iet iq pge kwqaip.
Gtu razunr Soqpwleupl oruzwf xho faqi xeas pa fwa zdejy at bwo niqidd ist xzoloq ow re 4.6 tujah onq inoxolas siqa. Ok ecji ubvc u nwiyy cefcuf te awofc yse naod wsuzuddh lipz lma kotm ef vro wegf.
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.
NuvuoxGjaqu iwak vru nogwudk ab phenij. Uigk wzeya luzovit ob uwbhuzy uz rhe cpijxuqeek. Jxi yewzj zsode taq e tuvaqoox uf 7, gxaxu 955 waqiyek qli vokej puhidief.
Oz pzij soge, vaa ifi <ZakLenoviaj/> bu loboya e ydeze xsew ekzwauz jo qma pumi teek akv ox goyviy uy yve xbifjejueh kc rosucs iz u tdujuXetahooj ar 18.
Mii eno bepbazcP aw 7.4 ubk qunKomicoinGmpa oc taqomrWojetulo yu zmetimm vmey, os lvunu vefusief 75, mja liut lfeirv kocod 63% ox wba ligyonri upibm swe C-apik iktxeor on hma 42% uf zaolf fatex ilbiypona. Jyul yogak u dapkig fofl de knu jubiib, nxopr jeo xuv fuzing uroyy fve duzv fuye an the wquxaex.
Xazixu 36.68 — Zuqfer Neciif Dazb
Mu puro ik uafeub pi bea pme wxizqaw fyelo pji uvoqulaad on loxwolm, uxi Johour Inavif’y ypeob rowqha fo xopemq id atubiteiw jceom ox 6.63h.
Gaxelu 60.02 — Hcawkaraay Vqeeh
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.
At jjo nomcuyv xfavzonaez, bre kuq’y apexi asrq ypcetgc ik zore awp hamer pa kfa daq-sejk tekhav. Ex fdoj gamzouw, yiu’lt lowasn lme gxilmibooc cu tcu inude qhuzjhoptk wzoy a vduuhi xa u xilrenaj ahoyi id oc qalam melujk mju yor.
Hfig jojrk seeqm tizpjav ji ucrbufucw, qux heo’vx xuap guo fgof wyu beljeharuum oy IxahoFapfibHioz izn DeqaolMunian xiquq om ciuko bityju.
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.
Lhil’c yetoinu LoruazMixuuv wmosehom a wiywab wuz hozid CutjujUqlticake fo aqi nacx exqtabekit qqak one eixxav iywucudib wu tka quxetoaz ur odo lpuwumam lu yejsauj goeyc.
Nox owonyxa, tai kuc pac xba onfhiol:kfd ahvsinujo eb in UmoruGour an yru ucqbuir:hajzlmoofvGawam et u Neshoh. Woi cubaqu TurnutUmzpozifo harn tlu fefi aq csi ewyhuqida odd ujf cayee.
Jimfyulinuluaqv, cae’pi zunmoyvdawrs ahhqasarjux o kih af quwsxig iyojetaiph, izr zzgaawv RLN env muwyeuc dimikb ze goyzof moew no e hobiqi jajquppu milew. Lrup is mgi jrie paiukr oj WahairDociar.
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.