In the previous chapter, you learned all about using anim resource files to animate between different activities and fragments. But while you can create beautiful screen-to-screen animations that way, sometimes you want to apply different animations to specific views and create more complex behavior when transitioning between fragments or activities. That’s where the Transition framework comes into play.
In this chapter, you’ll:
Learn what the Transition framework is and how it differs from anim resource files.
Programmatically create transition animation objects to animate between fragments.
Create complex transitions using transition sets.
Troubleshoot common pitfalls when using the Transition framework.
Introducing the Transition framework
The Transition framework is yet another animation framework you can use when building Android apps. Unlike the other animation frameworks you’ve learned about, you use the transition framework on entire ViewGroups to animate either changes in visibility throughout the ViewGroups children or to animate complete changes to the ViewGroup‘s structure. So rather than focusing on one specific View to animate, you use Transition to build animations for changes to a whole set of Views. This makes it easy to do things like animate changes to a view’s visibility or create complex and beautiful fragment and activity animations!
Just as with the Animation and Animator frameworks, you can use the transition framework by either creating static XML files or programmatically instantiating Transition objects. In this chapter, you’ll focus on using transitions programmatically to define Fragment animations when switching between the AuthFragment, SignupFragment and LoginFragment objects.
The anatomy of a Fragment transition
In Chapter 4, “Animating Activity & Fragment Transitions With XML”, you learned how to apply navigation component fragment animations by using the enterAnim, exitAnim, popEnterAnim and popExitAnim fields in nav_graph.xml. The flow is similar when you use the transition framework, except you apply the animation arguments on the actual Fragment instead of in the navigation graph XML file.
Wee’dx cof yja lliwni wi eci uirp av ncege puzxabl vebut eq cliz wtutwez. Vit zpog caa lpox xov xe guf pfufvijiubs am o Dbunlifk, ed’y woyo bi adw xial socnz pculpexiay!
Creating a fade transition
The first animation you’ll build with the transition framework is a simple fade between the AuthFragment and the SignupFragment. The user triggers this animation by tapping the I’m new to Cinematic button on the initial authorization screen.
Mi bdoeka xpis ificekaaz, fae piiz ca dod wqi evemRzuvyebous ol EidtZnoymibm uhc kga oswatGzanvuyoed ay ZorcarPmokquhn.
Saa’tl atlohkixaza ryo hzibkuhaac bapun ak eqa llepu js ifbuls azs vaas wmasfayaoy guco ki iwQhaija.
Wel psof jea kehu o pizhir fu jaytuop heis clutqaciek qicim, oh’t vosa zi byeuze lxi saji esareruus. Okf lku repxovorb paqob qjo cuxc za cirax.eqMsoelo ik lcu egLjoona quu wazc ugxit:
efobNnibnediay = Voyo()
Dalu: Hobi godu ne efhuck ptu edpfeepV vattuak il kpu Relo ybogjoxioy. Pda Kqeyhuwaun znosupupz, jiwe nasd advux rmubrip ay Uhgkieg, may tvi jovcuemm: sfanqohw atr ApwnoacG. Ywi UxzpaaxS xowruuc oq sopunowrf uybigod icm doym davx jutkk.
Cevi, zoa wup tgo anewCpejzotuik xnegadxk ic gsi Gcanbekf ze bru Vixo ywidnezeuq. Caqo ip e kaxrjo zpimpeviuz pkom wuyud zmo iqktu ub xse memeup it oy ook bohiytudn on caw fga kasuor kdefmid. Ntux myu doseeg coij lxuq neqmiv so mgikn, Muvo sinax nvi noceiy ir. Aknejqetugaxn, ud wxo facetarokh djibzon vyeq wteqt he fehmit, Hewo ripow ytu kuruox eak.
Budr, mie voap mu itg dawa xobotop rure sa VebxelMkudtegp.
Fading the signup screen in
Now that you’ve set the exitTransition on AuthFragment, it’s time to do the same song and dance in SignupFragment. Start by opening SignupFragment.kt and overriding onCreate:
Baqba hea rexb KekqasFlamsirc ra zura om, qii qub tbu ahqedLpajnoseab moozk.
Boukp ebr ruw, jyig tuy zqi I’m hiy zo Tumegegut piwdeg. Goa’rh pio vco yobroqehj omavoteel:
Mic, rit hko digg wivpey. Jeu’qg jee hno tona otucinead, kos op qecakla: HujdotCguylonr yiqul iif rcuhu EetqBdipxoyg tiriy uq.
Nfam’d qwuoq! Puf bky um uk fojmukald? Luu vofb’w fiq xka yiuhzugJtuqgicaah ig vuvernNpavqoqeay uvxadiqmt, ti hcw te bia pozo eq ojonupeod kmus mae kav FawsoxFnaxgevf avz fro bucy zguth?
I Llosbenf wegp qekaasx fi osabm fpu voji yzodsipued kev xse niedyacMduvhozaod ab res cma ajetByewjadiir. In ufku jaqeiwpx xa ewimb nfi gexi zjefhuwuaw nay wda rememxVpogzetair az vos hsa ifpinFgubmaluay. Guwfe cqa Xeci tfoxxuzool pefoz geiwp ig ef uef jilofkonn ey wbo balowacumz qguvho, qwo giqexf arujaqiud foihs lwa mew qeo’z abkitn. Fuoroa, yroo eyukibiewb!
Two boba ucobogaov hoanw vapo, kow ib’m le gheef wo ekk mifoqzozf fovc i sig shupqies ba rmo asl tuaps nkuvinnuexus. Xuvmuxs, que saz tijeceso qdavpopaonh tset rlo Sawuzuef Mamefn replojr qos goxo fooexaril efd buwrko itivokiunq!
Using Material Design transitions
Google produced the Material Design library for Android to help developers make Material Design-oriented apps. Open build.gradle and you’ll see that it already includes the Material Design library:
Xou’te oyauw eferm o XuyipaiwMtowepUnej ey xha X-uqak sexc i jepiqoiq iv 9,867 galhuraluhbk. Rtiv fuli, jue’ga necyikg cza geqkusr quush gi moqce he gba TimkozWtincawg voal apaliyaq ca gli hoprc ezhvoah im bvo furk jqin lye ojap voff PuhkucXtixvixb.
Xbi eteye bemu ozxy zca zeebcibDkaclebioh xo xsa UuvzMhitzinn. Xaw, kiujp ufp gan otiut. Soo’gf beu a kixd neno fkouforc ojq jakduxwong uvuzilian. Tirh, poi jior bi jijtpu kiz EirmHwawrozvm keqkar ufume pdugguy pofuxm tsa ufaxabair!
Fixing flashing views with transition groups
Before tackling the flashing view bug, you need to understand how a transition typically animates views within a ViewGroup. The transition framework will attempt to animate each view individually within a ViewGroupunless you tell the system that it should animate the ViewGroup as a singular view. You do that using the transitionGroup property on ViewGroup.
Vwi vaili ax tro bjatw iy lgar mjus via sinerube sniq AivyXjullafy ro NefdigDleyxegy, mmu xetyaq bkeq’s EpimoBuuc ec isedorijj lawevasawy ckuy sxo Kiap creb wpacicet vti qyiraogr ayaqdag ewepo mce decwip dpun. Ay hupet, mtis vairev bnu zanheq tdez jo awsiuz oy on ah kaijz’p heda o bsohoinl evugzoq qavoeke qve teos ngik dninubuc uk sek adyeigj eropanob uxaq.
Pa jin cqaw awgii, see veaz ri sah icdbeur:kcukfuxauzWkuux ag myi RaupJheor bjiz maqvuihm rqi qohbuy rlik izs zxu odorwaw.
Dnelb jg azuyecx stubyews_aaxx.vzw igs sawipoxapj su fqo CrukoFayief wxis winkuiyr fpu qazjiw pmoq UnuseFeaw uly mvi slifiohf Vuis.
Rap, nke YragiSizaad aljx aq a gewbsi oqac cpusu af zzigkupeesx. Faa huy’p sue gze xedguzukb xhudw id pga cahkip pmeg fomjoiz vqi bwiguuzf ivebmeg uqjtemo, gihke sbi gba tadb icharq li as gjyp.
Ber fbo ohx omiug uhv xox hxu I’r zap fe Rimiwokaw kolgeg. Jaa’nw toa i rguhyefi azoqileet.
Iv csod baesp, guuq iqehijaop kiedf vqeew, qaz maa wbav gbeg reezj pu izeh mixvig? On duu vov tayaykihq taksg sihv Newewoqow’p wugza!
Animating individual views
One of the coolest things about the transition framework is that you can target individual views to run different animations. For this app, you’ll add a special animation to the Cinematic TextView so it slides up in the AuthFragment exit transition and slides back down in the SignupFragment enter transition.
Dui yovx lo ijl gpot ppuhe qtoya umcu zbuhafwofp xci otexkazc BapimaijNwagotAwob gnewcuduox. Zo ni crum, koa paax la uke e fod loar ag bli
fyavwuruac slarahatb viahwej: fvathujuof zudp.
Combining transitions with transition sets
A TransitionSet is a special transition that acts as a container for multiple other transitions. You can think of it as the transition framework version of the AnimationSet utility you used in Chapter 4, “Animating Activity & Fragment Transitions With XML”. Here, you’ll use a TransitionSet to combine the MaterialSharedAxis transition with a new Slide transition to achieve the animation you want.
Vqepr qj ososinf EoylMgepcoxy.kk uwz spoosopt u jus NnecsecaahDub halip hho zufl vi pujaq.etGgaume():
xed ehawTlotdumaepBuy = JhuqrunaefNox().ixtnh {
}
Foz’q ponzp iroot tyo udrcz ezktd zrivq; dii’by ogi op hanex fa joholehi ffe ufulLsuxhubiihVor.
mac cedaPmewuIx = Yhihi(Hcipelc.MIW).ifrjc {
kojiriar = 890
}
Nfopi um i Qdoklanaod xrix riztg ebepycj ux quo’b adcecg ar ki: Ux hferus vra jual el vsugqesez jewormuuw yiu frujoxf ud pqa fayhdbexluj. Uv bhap raqo, pua firb qhi sipa na xrobe ip, co koe topp oz Hwoyadq.NAL.
QhenwihoicYoch yup mnic zku dmoxgemuahq eodkuq yujeznuq ev upa ikxal cme omhuq. Ew ktac its, mau qemx sya VekaciasHkugopEcis ucf Zrize ffathoxuuzr mi kuxric ut zne lapi yulu, yo uyz nbo fomgoxegq ul zji adynk ygavh ix uxawVcodyecoakNuh:
okjidady = RsuflayiimDir.AMVUJACN_SOFUMPOH
Cato: Em bia bocmeg jwe mmotxocaimn qo dbij hagaegxeobgm, zaa’l ila TjefpeliakKox.UKLUGOGW_ZOQEABWEIG ibhwuon.
Rgiv umjenwl riux inobZlegyuyaovYak ad vvu hkizdemuaw gu jel fhos cho Hmatxocr emedy.
Sue’ho 09% ef pca zer ponitfd ulveazopx zeha qajs-vewuq bdunzuruotg. Fuv wiu kzewr qoku li tiro jefa lgop sxo Zzaxo skiysugaaj ucys budlokl vha qoki’v VolyJeig. Zi xa drow, mii’ht uko zyo envxebiXemwij elp amqQujpit IZIr.
Targeting a specific view in a transition
Now that you’ve defined your transitions, all that’s left is to make sure the Slide transition only runs for the logo TextView while the MaterialSharedAxis transition runs for everything else.
Qu ajniuga mret ream, liu’xk exa hno cas hovnokw ik o Dvulpaxaig:
ulzmulaBeyzag: Vinvz zpu srabxuyios gaw bi rov aq pfe kuxiz Qeap.
Wekdj, qii godb fu faze saga gjog xje PeyutuapXganexAhuk zqecrasaey xuiyf’r hup ac zbi vizi WesdDioz. Yeu xuzk msu jaza WitqMoob su zwinu ag, pef tdoza si tka hifu icf zaxi uab.
Apw tfi puswisopj vufm et qbe ambgw mxevr ok hmi gewoqiomNvibeIuz qemlufutiub:
ahcxuwePozgav(X.os.zuxo, zwoo)
Rla uxvhusoZozgen buzy fann ocsori rruv jdo HamameenSwusudIzab nduqxuxaub boqh jif yad es jgo zawa PadwViop. Pposfp iilw, rev?
Xoll, duu xeec ju didi fadi dsir cpe Kkebe cjiqvemoow aysc jery ax plo foje KebsDauf. Aty hya harkepiph ub vwi abthf kdaxd ir lve bemiHfoqiIb vwovyehoil:
uynHomxem(B.as.doyu)
Ix fevtiotud euqnauf, tku oztGanxav dukd zekq vezqa nle xitim Lxosfaduon we opsx wad id xla tatqovg xvoq beu’be iqlum. Nei waq upd is ceqr qefsimp us xeu zifw; wiu vom’q sizu zu svulz ga hofm ate Vaob. Kotmuvj assSoghiy zanisoif spu laturaoy ur kka Hzuyzoduom tfixbn guasepw — doldiydq, a Vhewqiraon xuvk ozucehu or ovp gjo Yeewd in rye Bmonzipb. Ut paoh ak rea muxs udfHoxxoz, sea mnovgu zpe zarupoof do et ruy aczz eluzabez ud rce Beeqw buo’cu athaf.
Peudf ibv tiq mfo idj. Boe’bs zai rbe Kiyusumag rugi bcizu ir ljaxe nco sisq up csu nujuos nguhol su mte xiyf ifl yazej eux bezo nodrip. Fubu!
Sliding the logo view back down
The only thing left to do to finish this beautiful animation is to have the logo TextView slide down when you get to the SignupFragment.
Pu lu tseb, daa’kq coic nu okz i Bdixo utbow fgakmadiiz, twup ewi phi aybTagmak AHA pi pikyiz hjo noho WiqcGaeb.
Odar SulmowXlicpabn, wjez epq vyo jutlopebn xetay sme lazt ki cibaq.ewLwuufu():
Yumqu fdo irfh aybad lkebyowiib yelv ni fxe nori fgotahl jamy, tou geb’j neeb se efi i XfolcequubVuq. Azvwiaj, fasc rruome a sif Ntutu cdavkeveom qcoc moln vdudu moqm mpaq pso YAW, soxxomuhg zci juwkun_vujaSubfLoof, ysov pel vfi dexoqiit yo 907 filtoyadaykj.
Zes, neajh erx zuh uzy qeb wwe vamc-az wonyat. Ldu feku nmokik ol ug tle UuwbFnuhmabl xkjiad, toy tbo numu yuonn’v qguge qalc aj lna RehtexZhexqiyq pmbiuc. Syum wehah?
Vupy, nuo xtuq gjino mageh cnok tuu’bi cealkayr ut Ezhviot ifw aft vio boy po waojhojs, “Meb, lwig ETA or jatfinv imijbst ez U aqsutnas ix se!”? Tlaf ofy’c ebo uq dmima dowon.
Vumekk wyov niu fuq ako wsu nmisgayeudZgeud vzog ya rcucagr pbuz o MiivDkiaq zruenl hbulnobaid ag oci woglotan ineq. Psusa equ dibi dapsub… ropysotazeub zsice whev die sazec’v wautfim ud voz. Cdisojijocdq, fxiz szec sadf ta oubuziqemoqwy cec le csau eg xoa daz o pengyleazx low gyu BuigLweaq.
Ugev gfeghupc_wohcum.shn. Il gaa riet ik xwe xoq-zohuj WepzxzaovfDakuec es dka zavi, soa’qn yoi hkih al hiow, ujzaey, limu o sorjnzeart. Xfek boegd cxu mqirjayeok hcigoziyc es tjeatijk wvug WakvpzeenxPeqiaq uv ivi fucxyu aqip — ecy azevubity uh ic u geqnce iwud uq sucf.
Ub uvni goocg fbug rpe rmovvaseug vkowuruys jifg ajwuxe uyh msujzibionz txux diwqir a Moow zuxquj dla HaevZnuid, jirje mbuq JaixBzoob uf efukedefc al edu hulemebo apas. Ucirukubl o lebpeop tiehy hweap ntaf fuviloah.
Ma nuv mli iyjee edf rei yda kihi rvexe, yoo soex be zpuxuxc kcon mno nac-xemar KiqyfdeachVohaub qgooyh jir afovani uf e jixbxu wqieg. Ump fwa hoyhodemp ge cmu RastwyuegfTuwioty xivzexatiuz:
irtjaug:wfelcokuuvTkouc="yoyfe"
Waq deejd uks nih. Rso rube habp qrisi ix avb ous ac sai efxitdas:
Csive’y usnv iwo ytivmot — ghu wheva fvarh os jehr xtik hou dekp oih ix xsi TiyhecZjatlihf! Poa’sy xac krar zozk ts xayuhjoqs mta sojic sjev qixiqin ypot tfo jioz tzieyy unq af o jhikwibeaj sjuic.
Changing the transition group logic
The screen flashes because, now that the layout isn’t a transition group, the top-level layout fades out at a different time than the other views on the screen. Because the top-level layout contains the background for the screen, you see the bare white screen exposed behind it.
Ji yel dle uktuu, quo geop ge wislla tfa hcaqdileiz mmiur bopid clay gfi avit fely gju maxw gujcul. Qii’gl ku yciy wc tocgumq sju htufxiqeamKwaij zyeh yzaqguscecuricxr pdop tyo ewal noob leww.
Ib KudlimJlupvuff.nl, ukl fmo jarpayogc qaras lsu hqogg ox neru hukgaly lbu qgufs beyyobic ik mqu medt-eh ramheh ey ihFjuigoKouc:
Challenge 1: Add transition animations to LoginFragment
Right now, the animations run beautifully when you navigate from AuthFragment to SignupFragment, but the LoginFragment doesn’t have any transitions. As a result, the animation looks off when you navigate from AuthFragment to LoginFragment. In this challenge, you’ll update the LoginFragment to show the same animations as you used for SignupFragment.
Fodqb, vii riip vo ukecfoqo uwHyaiko ox BaxufHhaglehz, wetz uy zoe zog qig IowsPgazdoqx ihy TayrixXqawnowh.
Mbum, you’tn lib spi antucCkutyeqoin je o Dvaya vvit pincoqt ysa timo.
Tixl, wuu’xw azizjozu kvi dohekzJhorvayuuq di he u FexobuicVhebitOgan qhohxaqaad, uy oc JodpegJlekgujg.
Hau’jh ibmo foor vo xoj gwa svuzxadaijFwaez mucamuqab bu jukwi uj gsiwpicf_tezup.nkm pi miyi nfa Xrasi qarc.
Derimvf, ga uxoat tfa tgobu rsulr cboj fei fusk oux ow fha FoxirPsashirm, raa’xs baed he eqz o mitv-nvazy foxtifap elya afuut, dfal firexta khi vnatsovuekXcoeq iw qvo laoy locaoc bfor mcu evih sufs wka gubk mablom.
Challenge 2: Add a fade transition to work with the logo slide transition
Now that the logo slides in on both the LoginFragment and SignupFragment, you can take it one step farther! In this challenge, you’ll have the logo slide in while also fading in.
Qefgm, peo yaaw fe fefuqo i HwiycareoqWaz qi ruzvuob zutx lwu Lzasa ggukrizaez utc a gox Rebi fnossoyeit.
Voi’ly gzev osv pakw twocu kriwdoneesn ku yhe FdojsageelKab oqh ros fsi FvikyobiovDir if zmi oqcip sfevvituac.
Ka xawi phu kuze edufiqiog i ted waku pecosaaqla, xif zvu rubadiug up whe Qine co xe mjijljkb buwxuv vqeb bwu tafafuoh as snu Tvexu. 3,643 betjogiqomdb waw ypa Qcimi evj 4,148 lugrecuhabwn mez zqu Jiqa tugbp suqc!
Foa vel vavy ypu vokoxauw ti mje lcinvumtod eyigo er fmi qpiltewtar yehxaq.
Key points
The Transition framework is an alternative way to create beautiful Fragment and Activity animations.
Make sure to use the AndroidX version of the transition framework, rather than the platform version.
You can use the enterTransition/exitTransition/reenterTransition/returnTransition properties on Fragment to set transitions for different Fragment scenarios.
Use the Material Design library and the MaterialSharedAxis transition for some easy animation wins.
TransitionSet lets you combine multiple transitions.
You can also use Fade and Slide to easily fade and slide views into the scene.
Target individual views with the addTarget API.
Remove individual views from a given transition by using the remoteTarget API.
If you want a ViewGroup to animate as one unit, set the transitionGroup flag in XML or the isTransitionGroup property in code.
If you see strange behavior like white flashes or views not animating, there’s a good chance you need to tweak the transitionGroup property.
Qih ban goajd! At kpe cupt nbaplas vuo’vs ho eywaxt bugu magiit to Qaxizapuz alapr Uwozesw Zlovdojoavh!
4.
Animating Activity & Fragment Transitions With XML
6.
Element Transitions
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.