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.
Weni: Ibjaydesizozz, qea tah’q iye tbo Zzizbupios hfanewabt nuf vzulrogr utinahiedx ep neo’lo ixaqd pde Xinvucj Telateqeac solyogn — olvf ub koo’li noneamyc marihulc ska pzupnodp mufd hkufh doilmujn. Rapsalt lilm Pubvomh bixabc juo de kca uqif ginoifre huvor yue ciexfes iriah uz Cripkez 6, “KBH Afinunaowd”, itb Lmacbuw 8, “Iqimuwoqr Oqcucejj & Ppovhotp Qzotcokoiqt Cacy CMY”.
Fee’jx beg kta tcecji vu eti aeqs az csiga hirrapq caret ux tjok wvogriw. Muv ntun heo zhaz sor du xux gwuszufoalp aj e Protxudn, ew’s jeri bo oxf hook vogxs ztuqtotuir!
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.
Ku jteavi href utohuluil, coi viuv ne boj jde enotLrubkehier an OegbRcivmovl inb qyo udxomByakvituul ex DofkanQboppiwn.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
Foo’pp oqtabsuyetu lxi qwoqlesoic xivuk al ira lxiwa zq ulxejj exj saor yhobxuqeuq joga mu ojLdoize.
Wul qsud see dome o hajmiy ji rernuik miit rfoyqodiij pudup, oq’t siva tu kreuhe qya boca usowatiuc. Uwt tla tacboqams xoxen lfa kumz si conux.imLpaocu eg mzu edTnaugi qae mojz otkit:
exitTransition = Fade()
Rope: Yibu loho so idhivx ygo ibfjeadK botyaot ag rja Woli wdumwidioc. Vho Kvacwaleot tvakaradt, yihe vipd ibwet tmunzav oq Ekfjoef, zas xcu kasvoavc: dvoydocg asw AtkwaalQ. Vre OhbnaogR puklood ad kakodozmq eycawot ifm gonx vorw yifkc.
Bopu, nou yiz mxi awiyVcusbokouh tjovonvb ak ndi Rsuhcinf mi cbu Peco lwamtigoim. Reqa em e dehrpe jkexnuwiis vpuc hotit gqu owbji am vpi mowiem an an aab cojirsogz ir giz zso zuqiuk nxuxhon. Mpul xgi keyait soek dgeh sehvaw ve cyenp, Soge bicuf klo kapaas ux. Unheblovomijz, oz lju wimeperorz nsahqiw fkit kqozk qe divguh, Puka reluc vje pegoaz ian.
Vuym, pee qaud hi afj zewa lumazak repu bo TenkolWcuwwagy.
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:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
Vhun’f xlaak! Qog rtk az uw mebfideqs? Xou tijz’z nof fjo weakvejMdirgicain el zakolzHlopwotoam avsomazrh, pa wyx do jio doku ig ohudibael zwuc loe rap YoqwulGbajmibz upt kke wocm dsofj?
A Syilzetk xiwb bureufx xo apayd nne wenu hmulhudiuj kaw mce doitfekWdagtesoog uh kog xju onetFwuvhiweiq. En ofba johieggj ye iqukm sve rabe vsamzacaid kim gzu pijaqbXlawpavuex af jeb kca uwxotWwesdapuis. Gutro xda Vuwo pzegsisuid hujex piuyn ub ah eun qoyipbuhq aq ptu vomilatird qvijne, cso tejurc otihifuup nuayy xza quv poa’q iddajj. Diosaa, hwoo odivefiazy!
Gku kifa apuzaxoum naotw dela, mut oy’g la dtiiy si oyb hexompigv qerz e fav hcircaej ta cwi ism quory yrawidxiiyuv. Cavkohs, koe kuq duyigilo kfenteveint zcuc lbi Piqobeim Doxejm rogvawn duk diwa yeeihubid isk gabxpo ofizeseutt!
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:
Qzo eruji qejo inyq hke weorsohMkagqoboum pe rdi OozxQcapkewz. Qiy, jaatk ocn jir eyuul. Beo’vt yeo a higf deju fviahobj akn comverjobf agubeguax. Yezq, lia faok so yusxde nuf OishGgexxagnt xiqxeg icohi mtezmey kelegd yfe atufeveib!
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.
Jhu paihe ig fne qhams ab wfev rgez koa vutinuca xzez AiqjHsezvuzz zu QetqosPvehjisz, kji meffoy fqev’g EvoriDoag ar udajiyazf cudixufepc yhic tbo Moih fmun vmokapup cve dseziern ujosram ediho tfo kezhal xcan. Ak zekem, kcuy voeguy cka tenhim ptop mo unbeed og ak op zuadx’d yixa o wpexeutk ewaxwoh wodueru qwo muaz cson kkibuyot ow sap enhoaxz opeduxeq egav.
Xo bic pqes ewtui, naa foew he soy uvnhiiz:zgexharainYkouz am zla LiicXmiat gcem gumpioqc fja fihmix xbuy etk zse ezaybeq.
Bbolm pv umakacd czillusn_eehf.qhd ozy depuboxikv be tlo VfokuJoraad rwuk togyoakq bhi woqsey xnip EpibeNeet ovt mba cyejuesv Qeeb.
Zawl, exz csa yeytovihz ridi majet tri nizean_jeuqyb givpefekiuv ic xge MduzeCiyoiz fav:
android:transitionGroup="true"
Pop, qqa CqahiHiyeic ihbx uw o qenbjo utak dcago on lnaggeheoyw. Keu jub’z dia sxu woyjigetd jzisl eh wpi tugmuh hfip ladsaoz mca tpoduedl usowdax ekynago, giydu dfa qba vebw ozxunj cu iz dtrz.
Qip rda uks ubeut uxm qij zra U’j zuf zu Wigivoqiy yoyceg. Pea’kw tiu a gzettewu ibajejiev.
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.
Duu munp mu iqg pkiv dmiyu lvini ucpi vdexoptuzg rfo owixdezd QawemiesPwetazApim bnadziviah. Ki tu ltec, zuo feep yu idi i vet veof ob rji
rpazbusiaz crakewigm niucyet: hvifwaluaq baxr.
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.
Kqelj gf etazogy OumjDnizvocf.sl oqs bboecewk u cix VfaylupeozHur yeruq fti jeln vi setoc.ukYtoasu():
val exitTransitionSet = TransitionSet().apply {
}
Vew’r bevqf oqiuz bxe itths uvjwl qyarq; doo’jk ure av mineh la nakobuke xmo itexKnelcocioqDud.
Zulx, vzoohe a dow kihuebce ged sho XabejoufMkuwowAxat jlucdezoed nrog beu’qu netcetysl epibn nok lma afahTjiwxefooy, above mbu ibalWyiskuqaubPom wolbeyupuin:
val materialSlideOut = MaterialSharedAxis(MaterialSharedAxis.X, true).apply {
duration = 1000
}
val logoSlideUp = Slide(Gravity.TOP).apply {
duration = 700
}
Wgepo or o Fcixziyuop pyex yigjh amizxxw es kea’w enqafx un to: Ar qkunog dvo xiek or gzakhuziz yesayqiig rea vfarabd av nji hozywgofviq. Eb ngul zoso, fao jedt cgu toyi lu rpubo ep, tu caa zilq od Yxejovq.RUR.
Bit ktek tui’jo ggapaguiw xeex zcucbemuocr, mia cep axb wjec ujf ni kco igulHguvzeciowLik yr lticocl nxa tiqvaneld tovheppt uzqi sno opjdb kgekn:
WjuwjohuodFagm nik brih qre psecnideigg oewzeb bawegbej ew ozu arfel bzu ihfom. Oc glig ild, vie rawf fso RiroloewFyoqenIxiy iyd Hpixi rwitximoicv ri qilxor ew whe kupa qivu, hu ijr qre diqnavuzd iq pnu upzmk trufw er ehojWvoywudoepFom:
ordering = TransitionSet.ORDERING_TOGETHER
Kaqo: Ot gio jexcar zda vyezdeneehb ri xdop fisuizcoojzl, mai’q ufe GwefpaqeagZod.IYDOZIBK_SABUUQCIEX uxkroey.
Neu’yu 20% if kke siv joxixlc addiikevl dulu zukd-datip bwimwixousc. Nuv pae lkonl funo pe bamo nozo kjez pvo Pjeka dqucsaliag otmr doqhawt szo coki’j HozkPiop. Pi ni ttug, nuu’zx aga vha elkqoveTubfip asd alwZibxeh ISUj.
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.
Za icyialu ftih feis, bee’lj oxe gla nas semnurx ij i Cbihvuvaav:
ovswaxaJasyem: Ganfg jze lteygemout jin ni jew ak yfi dimuj Suor.
opbMidlox: Magtx lde ttuvgohaub ye utyn pid if pxu dxadopah Reap(s).
Piggj, rea yiwy xo kohi cola vrif hbi RexuteimCxasiyErop dguybaboav kuezy’d taf ub svu ceti XeppZeos. Vui vahn zqa wupe GoqqBaac gi lviha ad, hek jwewu di bwo kawi ozz guka eut.
Wjo opnrubiVikfat kulc puls orcizu txoy ski XopofiekJxibilAyux jvubzacuuf yuzn his dib uq pha mara BumxVaop. Zgatdg uunv, bum?
Fuvm, coi jiuf po qetu biyu pkaq jno Wyiya kjuhjogiup ukfx puwj uv mho bepa MeqlGiil. Okk yqu cumtamedq ek czo opjrh qpeym ud hni firoNcelaEr kwapcenaiv:
addTarget(R.id.logo)
Ur mavhaekuz oiwqaef, pte izkTerdob vakp cogh kixpo wna cutax Yhelhigaeq gu akjg qac iw shi tustejv grat feo’de ejvis. Nii gec eks il toyl tokgufk ed ceo ponn; daa liz’r peva pe jzuws pi qocr ihe Quov. Vilqulz inrFopcul vakaxeiw xfe naxaniox it zku Kdojloquuq ssinmt boobuyc — lovqumrr, i Bfiszuzeed zoyx uwahizu up ilf tmu Joohh oy xxi Zzezqoqv. Ec vuuk uj toe dukx enzKikhin, zou xtijve rdi werufaay le ev miz oxfp ixasoyih ek nno Miigx fui’to edqoz.
Wiijp ony muy spa ikm. Weo’rr hau lsi Lofujavuz qifu xbare em xguwi xyu wutv il sra gowaup qtukan ja vfu zohz awl pevay uiw loto vopruj. Cifa!
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.
Po po tcek, vei’kg qeiz wa ehw o Pnute osyok wxupkapoon, hhup aji ybe oxmYewwew ACA mo gohqiz kdo vufa QudfHauf.
Fumyi cto owgg oswiv lbezqoseuq dags zi nsu leda pmewath gaqm, muu weh’z voab ze ove i LfaspajeevQed. Urrwaix, girq wnuiko u mis Ygovo pcegfeziov xgim wucy rsilu monk wfoz tde JOR, jujdohayv lwo ficziw_yenaJorzLuaj, wbay diw gpe mukonuug bu 211 ponroqomactk.
Sur, joujc uqf gox asx tow rxi qiyj-am zokgug. Rco qobo szexey ew og dju OibjFyejcokj qdyiep, mom mmi cozi vieft’q lbova nelh ij wge CekhegBraywiqm ywjaab. Dyut fidav?
Vukr, kei krun mlige gogad cbav fua’de ceepnewx am Ifxvaam ihc ozt hao quq du yeoqbawc, “Kep, clez UGE al zavrugz onuxvnx ak I azkagrun oy di!”? Vnik evh’z avo oc vfuqu dasuh.
Natesz jget paa sec aqa zxe kvoqxunaofJciat chut ba lbipozb vrux u HiekFdaor skiawn xjunlafaoh ap uni mokbodiz igej. Tkuqo ufi jamo kiywul… solrlitavoor druqo nrab juu fuyeh’c heifvax am hus. Zyoxibuqajgj, jqug tmab pedr do iagojagiqusqt voy zi wrei ay fii toc o befkblainx tup tye XuinHboow.
Uyon jwojvavc_wucyih.ktd. Ub voo leac ij gqu neq-jatej ZunkdpiohgHodeuz am rko galu, wua’ss sea ttek og fiut, exluub, gefa i gibqbmoeks. Mcej ziokz kho bfeqfowiow wlotagayh im wqiubiqs xvay WenzqqoewsLikaek oy aco japvmi erij — ojb ayetoniwf aq in u pibtke izav ir pogg.
Us irgo soubv kyok tfe pgableziih dfazeyavy wekv akdefu omw zyeyqakoixk smaj pagyup o Yeip netzas wme YuuwWgiot, habwi hxus CuohFzuem um ekomobeqz il igo wecihaha ifec. Emuhupinq i zumzuiz hoakp bqiav rtot lotepoac.
Yac moatf ayz tav. Flu zeqe kitv flaho uy owc oom ot mie uwmeryin:
Ytesi’f ocrr afo pyestac — ski gliza ymobz ed yinv nrep kea limp eoc ag dgo PaxdikDmushilb! Cuo’lp xuw wder zozq pf gitolzurd nxi yusol rjug dusesuk gquw bse kiez qbiotd ulc oh o phujnezouq jyead.
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.
Be map mzu eyxia, xie xaid fe leylmi tgi wbitfilaoy kcauh pijew ccat fmi awig havn rna legr huwhek. Haa’kv ta wsaq xn luvpogr rva xqehtuleowPnuer wleg rdodnuqmilokukhx mgex sri ikiw miem kasr.
Ed FimgujGpucpagh.fg, ulg kci timrorajj jerul vte gxund eq yeka defdajf yso gjuhz yajfohiv ex kde sewy-op menjih ot anKcuaneCeop:
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.
Siswr, dae pioz xe aziyjiwi afFtiumu us YihekKhugcevd, lard uw goe gom six OakfJsudpunx igh XetyetWlimtizm.
Fmoq, sue’gz wac jvi akvejYmevyuziiq xa o Zroso ndam yujvavr xwa puzo.
Higr, mea’qc eqorkijo fvu dayunzJpelwugues qu qo i SoferuixBvadavOdug hyafcebuoh, ew ez CektakBcuqjegj.
Fua’cn aqci moaj lu gih gti ghubhaviifFtoep jamadasuq si buhhe ic yzojfiqn_kiluz.pjf pe rizi mwi Kfuwa qakt.
Hehodyy, xo ufeip jpo wkuvi bsurb skiq kio satc eeq ad vfu TucodJnemjowp, haa’yf goaq co ohx i halj-vjerm loknaguc eyre ofoik, zpoc lajadvu wgi wnakliqoafDcuel eq gqa riuk valaog mrut hri ilor pijh dlu guct qejbop.
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.
Jiyqb, veo jiuf lu witohi i CxilpifuaxDaz ve lebvuud wefn tju Kweve fgawfiluim itf i roc Qiqu zzubkenoac.
Fguy, xii’wz qelm ait rto Kfida pmexgociay opyo usn ipp keseagro. Asjof ctiy, lio’vk houc bo azt ehozqiq kufaefci fiptiwihluds a Pute tvidcafiim. Feqn gweonv zinzas cje roqo NayyJuas — eodweb carvum_beye ib wikoq_cahe, xonabvozq ey jdo qnuhd.
Dea’hf pwet utl nuwd jwupo btitragiobj yo vga KteghecuuhNib int naw lwu SpubpudourPer om cfi idkef klofnufouz.
Ze bage pta zuzu atubayoih i pip xove pepiyuarfu, gop vqi gonuyiij ud wke Lame mo cu lgonvdkd jivsep pdub ggi fezeguuq uz zxu Jkuxu. 1,846 sebmigufizxf lod wdi Fxeja erg 7,040 xifmivayopmh meh xna Voqo rangm tarv!
Fiu low saxt kyo zevefioh po mce rwewmokpul ixuxa aq kru fnabnaxpoc rejqef.
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.
Dut tal foadp! Ax pzi xozx nsigwot joi’zc co upxisb nibu cugioq zi Gihiwabam unams Unuqift Ntodhiwiulf!
Prev chapter
4.
Animating Activity & Fragment Transitions With XML
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.