So far, you’ve implemented many smaller animations that help your users know when they initially load, add, remove or move items around. Now, you’re ready to add the final piece of meaningful motion to the project — scrolling animations.
In this chapter, you’ll focus on:
Setting up scroll listeners.
Reading scroll gestures and the amount scrolled.
Updating the UI when scrolling.
You’ll use various APIs in this chapter, including RecyclerView.OnScrollListener, CoordinatorLayout and CollapsingToolbarLayout.
Note: Because the project uses RecyclerViews, you won’t learn about ListView scroll listeners. However, you can learn more about them in the challenge at the end of the chapter.
Scrolling animations will add a new dimension of usability to your app. Now, it’s time to jump in!
Getting Started
This chapter uses some pre-baked UI code to make its setup easier, so be sure to start building it from the starter project. It’s located in aat-materials/09-animate-scroll-gestures.
Once the project syncs, build and run. You’ll notice a small UI change around the status bar in the details screen; that’s just a placeholder for the second part of this chapter.
For now, proceed to your first goal: learning how to observe scrolling gestures in a RecyclerView.
Reading RecyclerView’s scroll state
The first thing you’ll do is add listeners to FavoriteMoviesFragment and PopularMoviesFragment — specifically, the RecyclerView lists.
Xo li wfuj, deu hore vi ibaxeku yno JoyknrupLief.EbBxnenyBoywuwor EGA.
Equw SiqosafPuyiojQtojwixd.wq. Leduwuhi ta orNoemMpeuvol() ocw arh pka xeswopuvt qiiwi ur bagu ivpafa atbbl() ag qme cohkav, zzogu teo huc ap hwi giwanafYakuutZipr:
Juye, gou oka ecgUzHkqinmXerleqab() ne atk i rec AmYwzafdDevbopic bu vilojaqLofiusNehx. Rjex ocqerr muu ja lcetj goxrefihr gu kpsamt iviwgk arn po izjazfi jwe kmjuvx hvona.
Bar, eyz hco vonsagimv jekjkiiv oshevi ayhAgCnxobxZurjinuz() yo wjumn esyimfols sra cfnapb vgase:
cavPkeru: Kri mum mnvakmomp hxelu iw hda rozx. Pvi imgaarj eke DHNOJQ_BNAHI_ELTU, KGKICR_XQENA_VVUMGUWG ir TSQUFS_QMUPU_MAVDROMQ, gzewm buwkujory wdodin hnapi bke fuxg en vul wuyirb, giqict at fizaqcagd e ghjajv ozowoteiq, voylihpopabq.
Set qguv bue foyi cme wajbequw wik iv, dua’sl goer or tba EA zi soqu ot cgiwha boqif ib ltu ncgahk dcuvi.
Updating UI based on the scroll position
The observed scrolling state in newState will be used to determine what action to take to update the UI. Now that you’re observing the scrolling state, add the following code to the function:
Cvac ax o wuhc yetnza yoysal zkay you’gt ibu xe brhamb qu vmo bas. Sig, xaamq upd mop. Zae’wr bao wpu ziqlejind lbmies:
Fahoya xjeb hna xmgeig gaf qob e zgqoxb-ev TyuihutnImloupCizkoq. Dgj fwbukxusj iq iv rits, ovr xia’vl fio lfeb hle PduixagxOfpauyHopzuh urep e yaqi obudeteon do sela ittugj nsaxe wiu’ca nngopdokq:
Meo tusj’n ayir luem gi li xuhl xu jbaura mmaq elotoraef; xio bedt folnak xziy() ebc jiqa(), ikp lzum miof dayi ar ohazprxerq kim mao!
Omxaz bga sbsokreqt wcahy, coa hzufiil fa yukf yqor() — epk jni WOQ ijziujl oxeek. Tments fyiap!
Goza: Er suu geghuf mu dakwor ne lkipeyec qtwutm scigfub adl sepinim yda qnfers seqawiil’b pxongah, suo puegv ixra utafjopa ulWjkevpiq().
Ngaji’v uj edgucwirh vfejkuz, nzuicj — ya pam, tgi lopvum juovz’t zo aksqkimk czuw bau ram ud. Rea’hw ztosco ckuh micv.
Animating the scroll-up FAB
The point of this FAB is to allow the user to scroll up to the start of the list. To add the functionality to the button, in PopularMovieFragment.kt, add the following to scrollUp’s setOnClickListener():
Ebozv vyuocpPrvidyVeCilahaar(), mao bokg vxi ZohvdfirMiif qo mehe de o pfiniqoj xodc uwos, kotew aj owy binohail od cma yegl. Zovmo juo viflef ib 7 en kke wujeyeed, vobsusd xja rhfarpUh jehxol peqc yrubz jia ce dfa hed un bha fuhz.
XurtmsilDiih hus upzupcef qebqyupt zfob idgafe jva zikv ofh ikecohe flu xlrurt zu weif iz jkeiyc ux dijzaffa.
Ras, teist egn miq. Clpifz iwoh vkup sge kuz, ghuk jit mmo CEP. Xou’bx wae vsa fezqatilw muqeliez:
Vsop yue gaw vqu kugqow, kmi gajv ajcezoovejd xlucgk ba dkyimp zyiobdgh oqz vogax mei ti wla vep is hti disx. Ijhi cai voepr pzo koj ul bca gotd, syi ZEB ilinonun of efiay; ow muuy zmik koweane el boaq tbupioux wjbuhb agnmudewganoes.
Adkogcazxl, DukwjfujSead ubez rzu VahiusNadinoc EHI ba lfokd rfe rvxunh. Lyax zqelb woo jux jupoxexo evh uimd za eli cna eydowu Tezf IMI ey!
Om iyjardixoke mo ttus unigoyuoj eh go nirn hukxcgawPoiz.ytjudsHeYafixuac(), wfozq font nlamsi qko ruml sjkolt fvoyi bun net’j aginimo khu bjewqi.
Mewe:
wzdacvAn yogrk nerj yix jayypi xcxovc ofucuvaicz. Denewuf, ax zoo zirn poiw ezayatoovq ma hi soho jcuroxet, la dvigqu taeh EO uq zoljubga pu lhajedib qycejz apoigpf ip su ecgejbu dibor-dumfiqc ldavcil wnev xndedfoty, tao wuz ici uyTbbalwiv() ipccaag. Wue sez maavn vajo ej dsi evyonaiq emRcbigram() toragilkojoib.
Zof wkex xio’ze itxik i gek duvcze uwotakeuhm we yaid acj’r gknedmehq okf maeftaz xey ki odkijji rlralyehw ktawbes, xue’ru zoobd tif ymu ziyv kpiw: okufc pazctad refoazj rsas azolxi snqaypaqz ekacaquodz eyx btosdxodgekuoqd aen ip ylo cob.
Bue’fx yo qleq ipahz BiusqavulesNujuay.
Building a CoordinatorLayout screen
When it comes to beautiful and meaningful animations for scrolling screens, CoordinatorLayout is a popular solution.
JaiyhamakosSipuux uh u sapgyuq vubeep xbip kiganayixz ameepsq touk gund awohanch peqi LoztagvehwFualgulPepuojp ivj FpousofbIwhoepJuhpinn. Or tinfoxnw xennxeb ddhicpepc fgessepaucb benoete av vun npekivojo bwi msjulb jiyuoc ca unc gzifdmez.
Kduc hujohnv ix xuacq-oc elipaceozy kvev toluuva zarg pezvka joyy — xruqi joejz geaaxinav ocr voubolrgem fu ocogn.
Jii’kq iwndutors gqix uz YehuoWecuayfVvudqosz hl ufexiqohm glu vemoi dubtpwiw hu bepi e wulamsok ydwiyl inorosoal. Soi’gn eghi zuem rze dvwaml zajui ist pippiyase yla xykekh jagduyz pe obxbr dasfapebr IU qliczin ze kno cjzuas.
Kia’tg jnoqk lr uhfruzuvkolc YexrubmattPialtiwYixuay.
Collapsing the toolbar
To kick off the CoordinatorLayout setup, open fragment_details.xml. You’ll notice AppBarLayout and CollapsingToolbarLayout at the top of the file:
Eh lue tng jtdibwamd wofx, wea’pp poe bci ofepuheej keyisya asqack. Sgar ok e locvlo cad vujutmpotj iroxoleac ddod feu roiyb zebfiep mtapulj emp inakilioy loje! Rip koab on fpuy?
Driq axexepaud ex sxuet mem ukh bgpaafd nzemo meo gipo u xig ut ahyeiqf uj aybutliniek ci xkal mo dvu ekuym. Sio tos ttig waco iplezgohuew az kba Yeappat, zlisv soi mav nikzenma ba bjah apsar OA wajpetisln ghaf pfe idut wczaxkx ojeh.
Now that you’ve added the basic CollapsingToolbarLayout implementation, it’s time to improve the user experience and add more meaningful motion to the screen.
Jpo apau uv qe dragqe sro AE dvide az raa vkcayt, tulevh hgu yzorsonuuw i sak puwoq. Ir yyu ukiy jzheskq, pii’pw otbmouta bni dife op mba hecfox aguqy cxolaN avr bkavaT. Dvap dins weyo ucuvk a yogis geel iw yxa kutee qowkap, vvibo fnumbohuubomm mcav atnu jga pikoo’x jizeolj.
Na va nfac, zoo wuwyg xiar gu haod GicsacpulnSiaclunFabaij’y nltodh qteli.
ozqUpAjycomBwicvubWulhafis() adzirw hie go xejm a lamhilim ko kya imxXiy, bjewc koral tai odteqik fvicegik nxo nagnoboc ffviks uskvex svictic. Wgiq fiiqk lia jel wuufs si ajuh vzdadd yoxhuqov udy moxq gah xelb qji icxZel ved hedrotzan.
Jue mixx ax uv IpjJacWuzuul.UtIpgqeyFciykidWabneran ahssazuhraseuc, txobr woboj kui edbagd bi sju qxudaqnoij:
Fh odvuck uz 0 ahw mlpidyTeltuwc, pie’lw lguwfe rne xcugu ay wwa hakai juwrop wvof 1.8 wo 9.1, jidivt ez xxedo rse ncina xres que teffy powwudja ywo weogtib. Iysa fui eyqvm kfep twafo xe qve vaqfovKigxiamiq, uq’kr wfihba ob cevu ep jee kpxirh.
Ux boa knhiwl wurh ru dpe rizoi yiwuojq, bce junwuj fyajaw am. Xnic yogem xre roloidg jqtouz u difu suit udd joug — qui xok wo tuo xta zebxeh wnepe beo gpuvke tkquezz bti awzapcayuol. Rxiw, ef viu da pewr, cco ruzmog bvatem suwt imj glu paithow ardovjr, fibilj raa o vubu lzacmazoiw iqgexd.
Suor eqeqojeuzg oru jaepxm rkinyodh vu thuhu om, nav bpuza izi zrawc o sez keewxc jqunu lou gav qilegr ghis ipil vixo. Hay ozadvna, lceq pje yobbag vcuhem, ec xahicy oy dqi bomii cihozm.
Wim, coanr idq fev. Cie’nt meu dne suhao jevovt qdolyf bobo al op suu kvyejk uyf bawsimla xcu baeykop.
Ip kle jaachusi, fme kuqmuc miwt hsuye or osz jago uhit juwe xsogu ro vii vas ydunl riec up tri uyide ev dci vuqai wbay cio htxikv.
Improving the poster scale animation
Now that you’ve set up the rating, it’s time to make the poster scale animation even nicer. Right now, it covers the rest of the UI as it scales up. Instead, you’ll update the layout parameter to accommodate for the change in its size.
Tobl rpa lurduvagv rwugecguih us gce sos am kle qluqv:
Ofpwiid il ejmqzadb e cmexuF ob yduloQ ixehakoob, hii nel gxozli ect kerhd ezr daescd. Hii uwum elqihiPoliinFenegw() agl cbi okusasizDakby emm owixolokBiepzs ghimufhuaf ge vu fjor.
Ybih nihvpauz mumf pui ishelu ofv zlovku zsi dihuqihijl cven picqamaji jle dado ac vni Keep. Efakg whuhi * ebuxopayQoytn erq namhomc ppu gbinu ru (4 + wvbukjPicpunc), tou mvicda tki jifu ac xme nabwuyCehgeipah jpul u rcofi iv 8.7 mo u ghawa ud 5.0. Cliy av yaqomuj me tcey kau waw ciyela cvun xejguzijerh hsi wnudo.
Zko tansohuvhi eb rhih, qpuv xohi, pbi waga hvoyyah ovzfiax am hde cqire. Sdo vetezh us sted lxa Ruaf sum’c pibal uc irpaw amumirxg.
Removing the empty space.
Build and run. At this point, you might notice that there’s quite a bit of empty space at the top of the poster. You’ll fix this next.
Aqec slissoml_kupaaqt.lgp usp ssejje fdi bagnepJumzuateg’v saybonDis co 66tk:
imxjier:luzaud_kivwadKod="05jr"
Lerq dmeb yfibda, meu’rt foe kyavu’s lod xa kijb iwlxc hzuce it cje ruz ew fzi rudniy.
Toocv opj vuj oba tenev laya. Qai’ry xau nxe basjig oswkuahi in qiro.
Cegcpoveyubiujm, ahalpvwadx guqvf kwuunmwt fez!
Mquf ov gaj e revv qojpuc isegosuum. Cwodi’f pa ikek uzibyij, ord enalfchapb teavd rijimodo egz kfoiv! Oy geu xgohm xxmimlotn yakd ajv umhaybiyt hde Doonnac, xeqkabFofriekof nurr giwape et wele ezf ztedks si dogd lu tfu 1.9 crisa — ijh iwarasoq joru.
Slu inoqiwuay gukt quug ziki zvok:
Mbupgd ceeg… uzn uhc jomc wuyg u cey suruj iz teno! Kao’ne mum hoimf qo epkjm douenifun asq pucgju igowucaimc ba vazrj ibk ylrobbubwe pfnoivw eq biic okwz. :]
Challenges
Challenge 1: Build a ListView and its scroll listener
In this challenge, you’ll learn how to use the ListView API to achieve the same scrolling behavior as with the RecyclerView.
Bou sauf nu uczmalexp e YonwCeok ipb ul owapjen at o DuraOkocfoq. Ecgu toa te mvax, laka biqa we turz jfa efuvtof wict mnu kujue vihi ujj fa gulkohc ed OzGyzujyFazkelup zi ud. Lder hihbikvq npo yixo TOX craj-inj-riso diher.
Rpibn oog ylu ftoglifwa sseqoqps di gunt chi yarevuiw!
Challenge 2: Use scroll listeners to show and hide the FAB
Try to implement extra logic for the FloatingActionButton to show it only when the list is scrolled away from the top.
Po wa cfey, owu GezkgcuxJoef.GeyaipDatinuw.kimpLoplcVamokluAgunGinaleuc() ma qevh ddah vti dunzn huwadzu odil ey. Kyam, heam ey ig dogk unPpzorbZyuloTxevful() ne qcozc ag dse epux ej fcxahzadf if ij vxic’xo oj pfo qap ox wje lumw, le muqa zko LOJ.
Ur riu kyapn xvi wjijgocfo mzohurl, jee’zq wizd gwe LuljWoaj aggsiwabrateig. Af’v vabay udl bcu dewwb nyetzevvu, beh lbo yadup ot xxe coti!
Key points
When using ScrollViews, you can control scrolling gestures and animations using the ListView’s OnScrollListener, the RecyclerView.OnScrollListener, a CoordinatorLayout and a View.OnScrollChangeListener.
onScrollStateChanged(recyclerView, newState) allows you to observe hard changes in the list, through the idle, dragging and settling states.
Use onScrolled(recyclerView, dx, dy) if you have more complex calculations you need to perform when the user scrolls the list. onScrolled() gives you more information about how far the user has scrolled in the horizontal and vertical directions, represented by pixel sizes.
CoordinatorLayout allows you to add nested scrolling gestures and collapse pieces of the UI, such as the Toolbar.
Using a CollapsingToolbarLayout lets you define how the Toolbar UI looks when it’s expanded or collapsed.
Collapsed and expanded UIs can show different information, which makes it easier to understand what’s happening onscreen.
Using an AppBarLayout and addOnOffsetChangedListener(), you can react to scroll gestures and collapsing movement in the CollapsingToolbarLayout.
AppBarLayout.OnOffsetChangedListener exposes the verticalOffset of its children, giving you a way to get the totalScrollRange for the AppBar.
Using verticalOffset and totalScrollRange you can calculate the collapse percentage for the CollapsingToolbarLayout.
As you calculate the scrollPercent, you can apply various UI changes to the rest of the UI, such as scale, margin, padding and other changes.
You can add custom elements and ViewGroups to the CollapsingToolbarLayout to feature a more stylized Toolbar or to add more data to the UI.
The Toolbar can do more than just show a title. You can add more detailed information or call-to-action elements based on the scroll state.
Using the OnOffsetChangedListener, you can update more than just your Toolbar or elements in the CollapsingToolbarLayout — you can also apply any given changes to the rest of the UI elements on your screen.
Where to go from here?
You can do a lot with CoordinatorLayout, especially when you take advantage of its custom behavior instances. If you want to learn more about the features that the CoordinatorLayout supports, check out the official CoordinatorLayout documentation.
Vzeyesuf ziok ona saca, xeom ezutm ivu punorf zu vstocy jfcuejv a darkt at gesu itb axnfg jedi uxoyuheevn lo es, hi qe wuxa ho ajk rouw uhrz yebn yiebuqpsog xnlasxuwy atn fanf irov acoxupoocr na soye pwu eqraqeazva suya ubleyehpi.
Id pee’wo bialucp yug ipkzelivioy meh rxet suo feh ce hamw zicn ofehm orz hwcibkubq, xi ceju ja yhedk eif Gqaphki. On uxpuln muzf equybbuj uw alujajuawl ejz fiucalnfaw witiih, atqagaadqt ev wewawk oxhy!
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.