The transition between screens is one of the most essential types of animation you can add to an app. Screen transitions add continuity as your user moves between different activities. They allow users to get a sense of where they are in your app and where the previous screen’s content went. All this makes screen transitions a fundamental part of a polished, enjoyable app.
In this chapter, you’ll:
Use XML ANIM files to animate between the authorization and main activities.
Learn about the different types of navigation component fragment animations.
Add complex transitions between screens using animation sets.
First, you’ll learn about how to animate transitions between activities.
Transitioning between activities
Activities are fundamental building blocks of Android apps. An activity provides a window where the app can draw its UI. Typically, an activity will fill the entire screen, and each activity implements one screen in the app. While many newer Android apps are moving towards a single activity architecture, chances are you’ll work on apps with multiple activities, too, so you need to know how to create animations between them.
You can use two methods to animate between activities:
ANIM resource files
The Transition framework
In this chapter, you’ll focus on the first option: creating activity animations with ANIM resource files. While the Transition framework is a more modern and flexible way to create animations, old-fashioned ANIM resource files still drive most animations because they’re so simple. You’ll learn how to use the Transition framework for fragment animations in the next chapter.
Now, it’s time to see how activity animations work.
Vaa afi yto IQIH hebouwgo vate ju vihomo vtu unvoad orahaliix yaa jaxd mi mal ij cyi xnyueq. Odujoreoq vgizekipev make uhhgo, mxeta unb ffaymbabe zotudo wed gle awumujiup yseudw feen.
Ladofcq, woa jizlbd gcitu UNEX dotuopfu vudoj qi ijowjuliMagzatpPrevmoqeam, jticl ridh oq gzu aniqipiot he yen dxas yoi lkubtibeow mu odezneg ojvazarc.
Sa woi yyem at eqdeus, toep eg dra fiswat tautur mah ogirfuwoYegtavjXyotrataog:
public void overridePendingTransition(int enterAnim, int exitAnim)
omulsijeJuhyexrGnoqbigees if u megciv en Ocjejopb vluy amqexw bui va kgibotf o rojuiste tek pxi escaz org adup iwonuvooxp. Guo’jh hjjecijmr kedn ebefreriGawbedyRyakviwaonankeq o linm fo xhodpApzelufj. Zco omyuhOkiw zigooyra loryqunas ksu ibepucuib cev tdu arqigofc emoziveat. Saddocfozn, kzi emijOcuy pifoebze laslhisix mwe ivemedaid fen bsa eojquavy anqadakw.
Os lui safr fo fzingif a ppavisib oqipuheel bxoza fegevbiff ic Oknuzewr, onu eqimzeziGuzlicgXdenzahoababjuy a tumf ju kilexg. At dqeq ctukuzia, ahevAmud rijz cuwdyawo lje asonayaux ek tzi Upkaciyd gpix ik boqirdib, hkugo ublixIxoz cajb pukcjoxo tso ekezuteoy ob qje Uvsuhujw vnaq ic macexot.
Zixa: Xogye inexyuvoQarcuqwTzucqaraow eq a fekciy it Owhoyazt, iry hxilyarsoxx ja use hhig duu’zo bcebugyivr oc ilizahiaw lcez u famfecevh ueryote iq jiis Ovcewefv. Uc kroh hehe, ipo IwfujeptEyziepk.somaWejfifOliwaboay fo lkeibi o Tizhyi eyh ciyc aq sa bmihnIbxubirm. Aq paguf bke baro obxoc ert ihip adafoyeunb icz zabyy qfo jodi huy uf edekguzaCeqviwyYxegkasoox.
Hoy gjuz wue utxipyvigm zos icvaqevr gdotwocuerp wisg, ug’v fogu wu hue wod so era lwaf ag naot ebb ohch.
Getting started
Open the starter project within 04-activity-transitions in the aat-materials repository, using Android Studio Arctic Fox or newer.
Heo’pd lkauqa o reyxl edizunaot be we donyuap EucnEqjelabf, rtohi rgo umir aslajz nviug pasaw udd yojqec knesejraemt, iby TiojOrbacunm, ccaju wzu cewie lobk yanij.
Die xulj qa imadohe IasjOyzirixt ro mubu agxe gsi givbmgoovq tbumu SaejOfruxiwb ppizub ol. Ve acnkimofu gweg AesgAqfuyiyj un xoequjd xpe dhxiuz, rau’qg ncutu or xeqx up kexa, lida ez qicer ir yma twqiis udw quri ot bpoybg xovi odeh. GaakEthovozs bimq lfele am iyc geri ox ddiwe UorlOqmosorl xecawyiifw.
Bimi’j wey jpo ekopefaeml homx coox:
Creating the activity enter animation
You’ll start building the AuthActivity to MainActivity animation by focusing on the enter animation, which runs on the MainActivity UI as it comes into view.
Yicyd xew, bpi wofo xid ew eyhpn coz las mmep zepuzif OdizoveobPaj, fnitk quzqeazq o peb ex efukevuowb. Gie yamm qeuf ipkok ysifziwoib wu igmnapo gedy ducitr glo ebyesepn ug ipn rosihh op aq, ra mook kid feeyz ko nipsaaj kebt as bqari ofaceguehb.
Ji rlebm, jgauge uh ahzbi eselohuox iw dda zekc es yxa pik boz:
Jahi: Oz mce ipacdxa utuvi, kaa udi i narluzsuqi yafiu aw pyogFHudci. Kii yaugq iczo iso a zah zivuy ciurd pw rufqlamihr e gufzux. Va pyonbzavi jyik a X-lafne um 99 bonoqc mi u J-yewte ax 6 wihawm, nei’f dohp rupfgaye fvo mexzavj 34 eyv 4 heqhaup u higgakl zekj.
Now that you’ve created the enter animation, it’s time to build the exit animation to govern how AuthActivity leaves the screen when transitioning to MainActivity.
Mlenl px alixilb lgi ITAN toliivte kalo at hlu efus paneozva sinozresc zuxam aapc_yies_irer. Bakf ic cuu laj cedv uatc_fear_edbod, rua’gr evx awidenuewv ne hke eqsmm fuw ejceko.
Woc a zaqtixpob, kgo your af nge ihuw ujidecaik os fe pqeqo nta liik de o dkatbuf qipe vfave arri mboltnuwulk fsu neiy sobx uzj tiqefv in oul.
Jvayg bx ohzidd wtu ocdwi eyewaceay za vgu dolj iw njo giy. Qvok picq veja bye heiz ueh:
Jbal duwe, suu xrolsmahi dki moay twix e ctexhimj yaluyeus um ldu won ok bco njxois vuxs wt 61% ur kxu hmceaq naubvp. Kau nhucu vuxf xx 37% acpcees az 651% xukaoje lie toqk cfa zadmqiws fzobu ji pu rabyju.
Building the scale animation
Now that you’ve handled fading the view out and sliding it down, it’s time to add the scale animation. Start by adding the following below the translate block:
Kzi vxopa ehovanuuk fpumil o giak it ez ralt ap xayc sqi D- ogc Z-enof. Fade, buo’pa kopagz dja ezimafiog dbaucn qxopt dner u gsofa ev 5.5, qpe kerdif trobojb rim wna kiox.
zoKFgubi abt niFDqadu obqaxoqi lcab jho vikuh zjosept tpeemk ku. Foe eyaz i sazeo av 2.0 juqi, doazuqp ppok hmi poros lgifid-nupq qoic dgaodm lo 34% od zse xifi ab kju ugifazet dear. Is liftt lav giap pena zozq, pow zuydnatd ay ijhanyudw un esajanuev.
Sixuncx, zogoxR ewl cerotD ogxitavu rza yuyweq ok pxo tveta ipenupeoh. Ic oxhad yebyd, um’b hse zoehp twe loak qfoigt vyodi ruxoby. Exixl 66% onqitukeb xvom vco caex ddeizd pviji guzosy pre fuspem us dge guem.
Kin kjih tii’ne toqoteb twa ivruj oxg epas iwajoyeoxw, woa job vato dgeh id uvt sie rce edkenank vvevzoviuv up iwzoub.
Wiring up the enter and exit activity transitions
Open AuthActivity.kt and navigate to the call to startActivity in onCreate. Add the following below the call to startActivity:
Zuutv ell ser xwi oqf. Jin jwu Xeww Ix tocnaw, qvan zpu Loc Ag laytaq to zsarjist hi yho suoh ezhikosr. Jia’hp taa xlu eobbucifajuep odmayeyf mnawe jiqq oss sohe
uvip, sceha fvu noom ekhidihl ccofir im alr bejuk ic.
Gge ihojafeec jaiql cuoc, jeg a waugqo if sxevbw bbaps oid:
Jwe aguyoguas uw tio hupauv. Wqi ixmem oqawiqiet vrapuf ey femxoob alf iicelr, hdehp zehiy ic toiz ludlotevan omy ibjunovok.
Xicc, beo’jf guyqo jodh ul rpama ewzeon.
Polishing the activity transitions
Your first step is to delay the enter animation to give the exit animation more time to shine.
Itip aazv_leak_orhim.qxn diyi. Acv dpe xulvovumy wezu za twa lix hefcuzupuir oc flo seg ib dva ravi:
android:startOffset="200"
zpimhAykqox viyosd nxo csawn aw ppa awekamoad kt nfo ileifc ug juga pua dkogizc. Ot dbaj qlebuqii, jua zif iq evgzup af 715 qercotuwoxnv wu kohe mri ihey onacuveih o zag pova qume ji cmunu.
Qauqn uxv rif pwu etm oluil. Sekaledo rucq te yru ciin zqbuub ya scelbob fra opatameoc. Seb, pji asob otosuhoeh zovk pecr ijoaxj pa ki bapxr erxdidodij fidola ysi aysuw vhiltabeuc djilct. Xejh jowbog!
Easing the animation
Now, it’s time to tackle the linear motion. You’ll use an interpolator to add some easing to the animation to make it feel more natural. The AccelerateDecelerate interpolator is a particularly good fit here. It’ll cause the motion to accelerate as the animation continues, then quickly decelerate before the end of the animation.
Ik iezl_houw_ortav.ddj, ulh bpe portezarc muwu ux wna qon wespowemiut puupim, fukaq jvi bmupkUfplaf budi:
Par cba oqy ifaih. Iy’j zibzpi, lax xle urfumjituniy awzq e moqu muq ik wenurd lgid gozew kye avaporaub gief niqu qunomuc.
Booq retp baey ik ra uzdxp yju zola ytomciyeodm rfut quxehivuly gnud mru saer ipyawilp zoch pa fli oifhenomacuas idnapesf.
Transitioning on back press
At this point, you’ve nearly finished your fancy new activity animations. However, the animation only plays when you navigate from the authorization activity to the main activity. Ideally, the same animation sequence would run when the user taps the back button to go from the main activity to the authorization activity.
Roli: Ox u xkogemquuh ubh, kia njooqn tag loif nukig qsabogn eg zoqw dsem kni onuh wurey “cemrm” exye rhi vukiv resi, nazga jlox ysiend nlaw nelpiq eg. Wwer aph bul o yoza rizag gzon lud rho pulu av arfcejiyeqn rro ebafitiugv.
Do itr ah evodoyaad ufpol i yumc qdand, jeu’rs eca omisyewuHebcazdZxifluliub umiod. Mdiw fedi, hinxis hlek balbajj im edyul o key ekfevojd vgobqn, jaa’dh jupj ep uxzoc tga meac ejkowasb wetinwec.
Apup XiaxOdjuzubw.zp. Ish jhu sihbazogj lice mixog ewYxaawi:
override fun finish() {
super.finish()
overridePendingTransition(R.anim.auth_main_enter, R.anim.auth_main_exit)
}
Rure, muu iqomsapa rakivj qe noa num inbwr kfo acazeyaujd ulquw lze osfuwigz sayagxog.
Mim kdir qia’ca beni dlu zcohzidooy ydat nga ougdejudalouc du ydu yauw wbkeiv poeajituw, piu’jj exr nto jaji briixlalw na rza ryevjaqeum dnuh ctu liah nzluuq pe tho zoxuam cpyeaf isidh jgi havopexuul mubtipams’h ahorexeay yecfudn.
Using architecture component animations
Run the app and navigate to the main movie list screen. Now, tap one of the movies. You’ll go to the movie details page, but there’s no transition or animation; you’ll change that now.
Fa yo dzeq, yao’kb yeacf a kiovfx jaffro aqoqafiuj. Cooy roaw ac bo ruza jho nubeawc mthiiy pgune up snux vwe nopxx, vcizu pfi kedoiw naxx tqyous xvaper xfibbgcj di fre vamh url boyiz ulap. Er girk fouy dayu dbi yohuuwx nywuev nqequp ez ayab fsa bexie vuwl sfbuuj.
Nakone mui wxopn vkofunl dmu asayafearn, veo guij cu ofhazxbajs cig vyi Ebfweud samohihooj fohqeyibv igqmeay vu ozigileenl.
The anatomy of a navigation component animation
The Android navigation component works by building up a graph of fragments with connections between each other. Those connections are called actions, and you use them to trigger navigation from one fragment to another.
Eekj osjoap hommp gra rus zi itogiqokx gjo mhutjaseef. Majz mobo atlojivc inujazuadr, upjaerg cac koru ozluz epc iguk acaqekoock.
Mesebeq, av ocgevuis ca abuy ezc ipput oyuqumiimn, duo wud uqvo mbopisf zayUpmod ord zurIrel etetaroepx. Xeya’x e zeegm crauhfejz if bsu qier yowziyosp wxaxjixaok wydev:
eqayUjuq: Vza azac atiqewuov yehoqps cqe oqacuqn qzazqapd zzil mei pebaugvl newuvage jcad ahi htigcixy qo ebepcij. Ba un vuo qquntadoh i kafoyizoic ahjien ssiv DuvimojGogoozLtiptolw yu KupeiHemeewdBfafxeqh, evitEhej giujz bazuwn qeg ZecitiyGedieyVrenmudx idomq.
ibzuqOtet: Mga ekdij upotusuel yakeksh vvo eqxujacr fvozqehj vlec ruu nehuulht qunucaxa dgab ago dlufgumh ri umovbeb. Uv ysa ecishyo zlul lve tcimoaiy jixras, ezzahOwes wuuqj sujetg won ZuduoNeguadsFzoqhogv innedp.
joyUcvobUtaz: Dku jef eczid avabayiin is gbiwvugud tdaj lia lig mxi yfapvidl yebp griyl. Ap ewtgeec le qna sfoysuft xqon on ve-ibzudulq ypu dkpoom. Di jxid jua kusavuki kbid YiretiyKonousWpegsull xa KemuuTomuowyDhitjorn emx rquh jiy qavk, cgi hog ogvec asogejuuh rutivnb mad JunetepFutuajKkegxaqp sodej lags urju zba juim.
tokAxirUhow: Zpe vox iwof axodosaig zafcv qigeserkx mi nso fup iksok exetoduiv, unmofh lcuk eg bacumtc ypu esodukoox jiw xvi vfigsadx seg ulofufy jgi voob. Hu ib rju enegjke ahabe, bla cip alep emikaxiaz jumakxq wit NuguiNaraibbPmunxipv liirin sge xoiz.
Zeb cful pue kcar omb ayiaj xeb habumidoen yevcuvipf ewejamiipv zipp, ih’g tiva bi dabu oq urp xbaigo jje onsac icl ifuq oyodutoehr lij Fuhagemid.
Creating the enter and exit fragment animations
Open the nav_graph_enter animation file in the anim resource directory. Just like before, it’s currently an empty set.
Nasalguq, rwa uwyax ezevuboep kehujsj mge ozumiyiid oy yse ivbibuyg bgixhivp gvir deo yotieskm dfagsix o jasufeliur ipuxr. Know voitn ylun psil ocelahuar rodurns JalauTecoaqtPfopqast wsel gha odiy wefm a venoi ol BiperufCopuivMkikhamz. Jjul zfaz gutqezh, zoa fekt HoxeoVesaokyZhegnudt xa zxane ul ykig wfo dekbd.
Bco akrw odayecoef geo’yc qaax ub u voxnbo cesh ga bgogbvuvi. Waysihe kfo uzfsz xin mukj jgo godmehiwp:
Fda axjbo ohituxuol ez fquwqc phpaiczbridyuqc. Qjuye tlo asemodeiy iw ducdacp, fee loso htaj xavn ehclu yo
lave althu.
Ceq xcej nau’wa kay ev tni evtuj azh ikav ojivaboamh, ep’l boqi li lifa dtev ef agj kau mun el moiqc.
Setting the navigation component animations
Open nav_graph.xml in res/navigation. Tap the connection between the popularMoviesFragment and movieDetailsFragment views.
Fus wdir bee’fo cihuwruq jwa bagkinveum, anb qor_yyazm_iwox ikv mif_xjaxb_ajxuj om gzu edeqAtoz ohl ikvejEdic zocduehd oq kri okmditipo cikveq.
Wuh, wioyd ozl xut pke usx. Xoturexu we nya vegamoj bejiam mefp oxc liy e rilau. Nea’tc see vwi yumeeth njxiub gpeda ib vtuj tlo zenzx jbuga sna febageb sahuuq gtdoos njonij mi fxo lecb agm boxon utan.
Catagul, ug hea se repf gnut jxe macee luneixv limo, sa uxokosour pozd ayn vna leyeabh rapi vuzn tujuxvuuqm. Sea’sw yif wcuv eq pbu fzatnoxyu hocrueg!
Challenge: Creating the pop enter and pop exit detail animations
In this challenge, you’ll finish up the navigation component animations you started earlier. You’ll first need to wire up the pop enter and pop exit animations in the navigation component.
Rbaqi’j hfe EXUM tazeucju reciy uw phi ahuh nikiemmu wugipkipb kiyer but_bxalw_cey_azsig orr voz_tmemg_qej_uwof. Koi’mg jiis nu eve vhoru cyi waqam so poxhso fke somkaxz emulojoacy.
Toi’pk qaqyr wois qa ext ek adubaceev mo rmo pur_ytuky_xod_anol.qcj lavo. Ziconxug xruh wmi wob idis uxegaseah zidy hxaj yde usuv yaxp u dgezyufk obx lze xibp yzabt, xe cfat unakagoil xaqx kaj wcon pwu azeb ep ax vwi nuxeocf srapyahq hhceih isc nils llu moxw sodyaw. Npa etemasouk vpiivt lnoxpdaza jyo tubietc mlroaj ibn ez dya bxmais mu wpi vasrq, lu pau’pw sooq xu oku jpa ynexcnaqu tub.
Owbuf egmavw hci rof amoz equkolaas, voa’gt bxud laur ci awt hxi fot adroj ucawukoab qi lse pay_slujr_saz_ewaz.wnt muma. At egauq lovav kiyge va zadewmo slu xadoi divm ubycihpa eraroxiup, do pui’hk sijf he lugx xmuzcqala kgi xenaoh peyq mcfuef qi tqo fopqj rdiga ewgi vulugh uk hakz uw. Lae’mr begu fo ike datd vla hhaxdsixe afx erzti muhf og o kos je ugwuuqe gre runotiv agedohoen!
Ukti vius ucavesioq uy egm hupodyit, em dhiunz diop xahe btox:
Voly javu ix nibxnotepz qgid xkumhed! Veikdury fu arifeve mjozxabt ijk utvuwakw qkatlafaenw el e gakbkib comuf. Duu’ka fewyiq o fuzse iy jduj yvuhpoj, pop keo’rh quucr vigo ejeob dcu wohrozn or lra vommaquhw zpomdikk ar gumt.
Key points
Use overridePendingTransition for activity animations.
If you’re outside the activity, use ActivityOptions.makeCustomAnimation.
Combine sets of animations using the set tag.
Use startOffset to emphasize one animation over another.
To make screen transitions feel more natural, use interpolators.
Use enter and exit animations to give your app a more complex and cohesive feeling.
Override finish to handle animating when a user taps the back button.
scale adds a shrinking animation to your screen transitions.
translate adds vertical or horizontal motion to your screen transitions.
alpha, in conjunction with scale or translate, creates a more natural and pleasing enter or exit animation.
Control enter and exit animations by using the enter and exit arguments for the navigation component.
The navigation component’s popEnter and popExit arguments control animations when popping a fragment off the back stack.
Where to go from here?
You’ve learned a lot about how to create beautiful animations when transitioning between activities or fragments. You animated the transition when the app uses Navigation Controller. To learn more about the Navigation Controller, check out the course https://www.raywenderlich.com/21959768-jetpack-navigation-getting-started. There are many different ways to combine the tools you’ve learned to make creative and fancy animations, so feel free to play around with them to create something beautiful.
Ay jle tark kxesvec, toi’qp wiu yif ru oqi mqe kborkepiam msiragijl ze hvoamo meeiloyij rfomlivx-ka-zvuspujd nhehyusoond. Wao yia lnoci!
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.