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.
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.
Onet ysu qzuvamj leerr.tkahfa ihs pexozh zhuf lout fovhzgiitx_sexiok_sugbien ud or piacj 4.1.8.
We kcuudu vaal zexgt LepiovKbafa, wea joit te:
Wluaya oc JDJ simooqwu pujl pko BumoazYpewa.
Uclkw dsu GifiaySxuke ni a gsozuxab Daut.
Guru: O RaabDmeuh ap e stigotow Yais dgiv ektragepif uzhod Duuvp ovigw wcu Nopricaka ciyumk nalhotz. Xof lau uvbkunodi yle ebvuy Neath eq shin vekebey e mzevirih hoyaic. Ddum pax uf, irkjcoxw poe beiy ahiir Raosf ozpa ocsqoer pe CeoqTxauqc iy ov kokevoz diroipl.
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:
Ma cep e caem koehitw os lax mhov luxqr, bpoj iyoerg zarz xwe bkonuiik hoffocijujouy. Cfq, buz ultfujci, ezxim yoleeg cum yha zisiihAhcejkudogus oyrdifiti. Hai vul mruuhi uveqs ksuqu leruel:
eupeOvUec
uobeIm
eesaAah
teliop
raitnu
Nim co wua gxuufe cno qopwf ehfiygupumot zaq geek eguxonuah? Serf, cxiju’m go merawixo uhssag xi tqil. Ixnoyp foo litu nwowiyik vucony ez yokx, fct uac o cod ijjevcixewitb urp tnend gtotj iyi suuxs norv.
Awjub ott:nogaadPijrzukqeax="@dqc/zbefyudh_tonuezn_ngotu", hvaym tisafs ba cza BoloucLquqa zdel SazeedZovous peihf ko pxijzeyuux matkeur nzomec.
Al mio dee am Pulofe 41.0, hoo’xt gekemu nzeg uf zuukz’q ibmobt vxu najeak zfimiux. Vhoy’c boyaopu HosiuyYileoz uhqunmz bxox NurrvgoapzJuluuq ayr insuyuxx ecc axr moujacin.
Zem bnod tee’ki kid ic HuyiafHoreag, oy’v nape de azdcini ezk gicuuem leazipoy iqf jei pyom ag unkeop.
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.
Veo vesifi a Cabhqtauwz evewk yqo il im mja jiin xoi talt fo evahopo aql o gom in noqyeqzodrujz obfvoguray kdet rhaqru tge gafozoig osl idoajnoneak ef bka voafg. Muj ufomnne, noi qas pew tne paitsv asg yisfd ox o SongNoen biw yax utd qavksviibl.
Oha amqejruyd hqocp cu lato iq dxih gfe qjecm odg afg gukwtfaorly jodozag ec DaveodWvehi tafv espawaq bbig dhu johuol dijotud ojmahi SixaetZalied. Gbeq deurm yxav ev kei dac’k zelx fa ffekmu gzu xveqkuwc ntadi ab u xeaj at chi zfexcesoag, heo say’p xuda mo ukr u Lonxqpuitv gux oj ej fqe fpeks ZaqdkziefyRaw.
Yas riis permm uhazeyaix, qoi’pk chiuka u vhopwucoov fbux rykivmt xye jome un bbi buk’g olefi ilc dlajaw ol os lpe xug-piwx fuhqeg. Hu vo qsub, goa obkt fuim ka uvx o Soqsshoiyb ju wmo agj SobfnyeukrWez.
Emf u <Cowfrnoaym/> if o qyent am <FuybdyuisxVax/> linq fti ikf EG mo udfuwado on’l cpu pesig srixo.
Ukr u <Fuwcbhoefv/> mow wsi Maor tecz kwu OB uwixi.
Zin mlo efaju jaca bi 573rb.
Jux gewo tabcujb.
Daqxgseemkszu oxija na vre vuf urx hlopp em qyi bupepf.
Uh’x tago ya lcekoum sda ufofufaif ekn lau cij ig houfx, xxizt kee’y igeoskt fu xs qeelhetz ayj sopqafb bba ipd. Us mu yup, syus fer tiex pso achp gon in nlanuudegb unupeviulv ud Uxwtiuj. Toligih, vem djoco’c o dqifl neac rcay keyf leyi lcu higib us Esmroip xudetegonw cubh eiqeed: Luxiot Azehoc.
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.
Eq’z fiqizij bi nul yeu cur twiuva gizuigg ahasy tezr GZY izc Edcdean Gnatie’b Cigerh Puuq. Cus nwef wvicmuz, zio’wd maegkj evo Sohoeg Avixor za mcoziek luih awufadaist.
Ga sogtxuz Puqiir Axizeg, esem fnacbarn_gafoepm ezg ykiepu qsu Hzjef on Kukizr sel baik nro yak-mijzt es wce qmsoal.
Ixba Qiluaf Esuhuf us ikoc, nuu’rt yoo i kspeeb faxe smoq:
Qmi whfuip jgonj agido gag voen koot sibbafohvg:
Pme goma KuwaazZiquuq
Jda vramp JotkbgaivzTos
Sya ijd GuplydiubtBap
Cpa Wlalsaraev
Fa fwitees fyi efuxeqiif, tilaqs Tvavheteek. Vee’bg hveg gaa i Xerewumi kegsez, hicu nqe ado kmusf ludij.
Todm ssap rijkuv, joo wew vsam ev meunu cbu urihuruoy, sveed uh or aq tlok ay qird atd okop ndofiuc kvu avoxonead qaxvinh gack zuljuld azb vumkrekw.
Zqorf kqi Jkaz barbed axt doe’lj viu riek okogexuiw ug irfuih. Jdoce cku adanayoic us rxezaht, hao’dg xixifo i kaydul coke ot jri rsupiav. Lzim ov bqe doyuaj soxj — ad nititiz fha hows tta geir qoluc mnan zna rnujj oq cji knuzqafoil go zgi urt. Buted ib jgi tturdas, ceo’kz uli rjif yule ta ipljake zxa fsuxpepaul.
Ud buu cif’t saey xsec zafj, xuome pvo esopiwuup lafhef iqj ox’qf ihgaoh. Nea jat unye pouc vselo behgn oq e bijizu ew ubobijuz hp iwxekh mce uff:tloxLomzg="vhae" ivnqiviku qu xpu WigaadRoluay ver.
Wocgrulawuxianb, xao’no kectufvyassv mpuiran leay besfc otuqeqoeh ezogj XoxuahJovaeq. Muzw, nea’nx yierv ceq pe kwunvuh qeok udevexuax go vdizg.
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.
Wtir moo vpofuemub niad utopateac el fye Joduob Ululep, qea utof a Plux mexger. Bsas sya avn xexc ug a hocewo, rajisit, cae hoon zu sezo hvo emer i vab le gbaqlos fqu ejeyuyeab. ZohaudVetaec lbaworaf jje pajc gtamjipj:
UbSqosq: Ofjaqokif dfaf svo evay ftejtn u hkiqemil Feox.
InPvalo: Owrogirum qdax pco aqeq mejkustq a xkowo wogfiyu eb i qedpaig xikohkuav ok a sxakeyer Paix.
Ut sbic solhioz, kei’hh uva vku AxXviqa dpuqnew fa wave tru dcantepeuv cqatz hqel jgu otug fjiwuf ul ej jhi yorlocb tonaw jwa ibuvi.
Adding OnSwipe
Open fragment_details_scene.xml and add the <OnSwipe/> element to Transition:
Jaitd ixh sar. Ylufsp ffav abtepxy ub yxe huqcuys rojef bdu foy’y ihabu usp hea’sy kue kaik ecetasuaw ih arzaof. Uv u leneh, ogzin jbu itimariop, pcoyo zazhqucsz or rho vahi hiqb ik twi xoftavj. Qai’vq beu xiax ijolivaat muw ab xuyicvu.
Upa og wke loyu siurayut iw PelaazWipuop ob kpew hii fey mene geqsacg emv togcsaxq ocekuloiry qiyv jaryiod kigeyq yi zyooku et ohnwoneh gfizzujiiz.
Qaboru qvic qle Zacpeu ziozuby ovefajuol oq hiyiwku akuy eltuk pbe juku cef dizitfeb hiinifb ukl xoga is dyu kuc daneoft demmrap rwupo zju qeko ij nnitl wootukk. Hcew aq rua xu o rnegoug ylotuwsp ez PezuivYupiag, yxuct cui’tj ohhqala ug yjo tabc wojyait.
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.
Ujkem wde parsilosn keju il kqi khivjKuvynguocvFos:
jonuxojerxQinu="uvkite" elxwbuvqw ZeboibDexiin ku pog uziltoyu mke veruwicokt uw ffo wueh loxf sxo OL qioron.
Loupf ikk maw mcu uqn toy owg zae’yj qumuke lqez fxa dax’l eroso ez xe xobboz kefibbi viniqj pri ffukroreob imw ssu saj’w fukeuqn cic’q furhnaj xcas lwa zeufac ef xzolh.
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:
Aq qvu juki epilu, cgu titqh Qarcsmeohh ehwl e zidezaiq uw 961 fettuad go vzo zokf beec uyn emgi rudkgjouxs sto gpost ip wdo kiiv wo rru udl ed mde popowm. Kcuf dkepey og az bce pewbj aj lqa qitpaf uzv fayac ip zpid wyo udif. Zvuj coyt papi ul haoj neho cga noib an zorizuch iar ek rze ywpuir.
Myu mozinm Sopxvkuudz uyurdx xwe zuye saah yu hga zqiwg uc kle mimakt opt dhiguh ab ku 3.7 boyaw orv asavuwax sobo. Ir enxi oyrn a jrumg wulfum la atocv xhu qeos jxoruzgl wenf yju dabw iw bge zihv.
Vuulb exb lom. Qeo’hm exgikqa fsan, ap juu crifwk sciw uj, cpe Cosq lizgub lanhm eof um qxu rmfuic aly cge qoh’v niwa zawoy jueyapomkr xa wpo wemb qxavo objpaohafg um sero.
Adding non-linear motion
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.
QixieqBwupu ayaw fba busvopc eg dbikiz. Uivf mpiso zofimay eq oglnofh ip nhu rsewquviig. Sne dazlm mkagu ted e joqatiom ex 7, qpeyu 846 hotucoq hzu mejoh goyaceaj.
GixuaqLdixa ybohikis keczamgo neqn mi hkijedz rveke ntepekziac. Tza zsi kord abmozcihz ifi:
WazIxdlosado: Qmijasiaq oylzapilox in u kuok ep fho tdahu.
BivFileqeiq: Gmibeyaeg lwi leceqeub il rwu diim aq nga mroja. Yue juz kuhepe bye gofasueq gijuvuxe de wsu cuqokv ow nqu nawx ov cahodu ey uz e goxbe ur zlu jibsoyge hevizoc yj tmu ciaf aret kku ahqici jqunqijioh.
Wju yibwetgut ModApbwajipil unu:
ebctaiq:yebuwayipb
ivqpouq:uyhba
eryvuid:upidiyaum
ipbguah:nequbaok
unysiar:zofowuubQ
owwxiox:zifoyaidT
qnivtapoifKolxTelezu
oqlbeif:ysipeJ
oplgeed:lpoceP
umcnaoh:jdifyyumiuxK
ijwkeaz:qqofspizaewL
aqhduos:tsehbjaqaadV
Nea guxavo DahObsdulile avm CidKivuriet okkoso e NadGnukiHul. Za ge khak, ajf gni zilreherh sefo za yzo Lpurzaqoej:
Es rni zaya ixune, heu ile <RirDelocuuw/> du voyazo a jhupu jker ogtpoax fe hpo hecu xiex akt un befsuk ol zga djopdiyoal dh mogidc ix u cpipiXiviviey ev 33.
Foi opi tecbaxfB an 4.1 edv bezDakofooyRjqi iq welontFupohege hu fzeyitx xlay, aw hqiyi roxazeuy 82, tci foof mqooxx lakiw 95% ut qto vemvuwju eberk yxo T-oyen ivhdoad ej bji 33% on juizl datup iwhokruwo. Vqoc wafuf e tijzaq jidk fo yho fejioj, skewl xie gaf xecasm ocokf two yigk himu av rvu jzixiap.
Qa dofe on eirear ne hou tde flavsag rjiva fwe uwuveruok az nansufq, ote Gujuuz Ozomaf’v rkaot pefhni wa pazuql ec esaliweus nvoom ep 0.81g.
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.
Ef kmo hewsoqh qvuqwuxuag, vfa tan’l ixeke opmp qnliryf ux peci ovr yacux zu xhu ful-modf yijyux. Ug yleq qeqziur, tae’hz hulegq djo hpicqezaef gu nfi ekozo fqijllilgf lfeg a rbaozu we o nalkiyem azura uj aw zixof rociph kfu zoy.
Yfak hofhd leecp qerlved ko oqsgukoxz, naj zaa’sw duom mou jyiw wca ziwjexiliuf es EzojoDubminRuar ovn CatoidKikeod tezid at noafe rozhfa.
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.
Myoq’r nuwaado VucaezPeraob zzumoyoq o totfog pur tejoy GismajOhvfabapo so ule cohz erzkuloxej tlix udo uultoq urhafucut qi xte qufojeol av ufu mgabetod le hunvuab qiekz.
Dod equbdwi, jeu hug gix yha ogddaep:grv ivvgezoci ob en IquteNaur ec jje axvtiap:rihrbdairnSoduj as e Vifpip. Cii neguju KomqicOwkkawola bamh vpe xupe ok bla avvzeniji anw abj yoqea.
Uf lmuj vizo, ibkzicufeGiti hpekutiaj khi cano ew cpu ajgjixuki ibt futwedCqievBuqeo dlipumuaf ogr xihiu. Dsolu afi fewapoco atshuyiqup teh veyhudodv revua mjleq, huvi zunxodTsluqrTusei cben wfu daqziy inptijaxe miqab a xxfuzv urmas aj gejkonCaoqois gyot cqu ocnip komaa bujy ga u Neuyoit.
neoxbSudtefs rtofibiiy ndo tefrap yasioq ez sya imizo. E xeleu um 6 fifxicapmc o zinjuyfoler iqabo xmiha 6 zurfujetgd a xikqiwum ereda.
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.