In this chapter, you’ll begin to build ListMaker. An app to help organize all of your to-do lists in one handy place.
Lists are a common visual design pattern in apps, they allow developers to group collections of information together. They also allow users to scroll through and interact with each item in the list.
These apps all use RecyclerView
An item in a list can range from a line of text to more complex content like a video with comments below it — a common style used in most social media apps.
In Android development, you implement lists using a class named RecyclerView. As part of this chapter, you’ll learn how to:
Get started with RecyclerView.
Set up a RecyclerView Adapter to populate a list with data.
Set up a ViewHolder to handle the Layout of each item in the list.
Getting started
If you’ve been following along with your own project, open it. If not, don’t worry. Locate the projects folder for this chapter and open the Listmaker app inside the starter folder. The first time you open the project, Android Studio takes a few minutes to set up your environment and update its dependencies.
With the Android Studio project open, examine the project structure. In particular, look at the following files:
MainActivity.kt: Located in the java folder.
activity_main.xml and content_main.xml: Located in the layout folder.
Kotlin (.kt) files drive the logic of your app. MainActivity.kt contains some familiar-looking boilerplate code related to the Activity and Menu lifecycles.
In previous chapters, you used a single Layout file to build the user interface. In this project, there are two Layout files: activity_main.xml and content_main.xml.
Why are there two?
Open activity_main.xml. With the Design view open, examine the Component Tree:
There’s a Toolbar to display menu items, as well as a FloatingActionButton. A Floating Action Button (or FAB) works similar to a button, the difference is a FAB also adheres to Googles Material Design guidelines. Don’t worry about these guidelines for now, you’ll learn more about them in Chapter 12.
Keep scanning, and you’ll see a component named include. This is where content_main.xml comes into play: The activity_main.xml Layout includes the Layout defined in content_main.xml. This is how you use both Layouts in the Activity.
While it looks strange to take this approach, it’s useful when using a Layout in multiple places within your app. It also helps when the Layout is complex enough to benefit from being split into multiple files.
Open content_main.xml and review the component tree for the layout:
It contains something called a Nav Host Fragment. We won’t touch upon these in the book, for now you’re going to replace the nav host fragment with a RecyclerView. You’ll do that in the next part.
Adding a RecyclerView
Did you notice that something important is missing from ListMaker? That’s right! It’s missing lists. At the moment, there isn’t any way to show a list, let alone the master list of lists. It’s like Inception, but…Listception instead.
Opew hodsosh_tuac.gnz al xwi zepasy soab. Cmew, bufutr jqa Xon Gixm Tsursufc ayz medilu ad.
Vupy, gi ba qfa Yimazyu ajs msidj Wozyib.
Hrazz epp zbex e XuhrcnabMood cmav wvu bufl uy nuyrufirth ezji vro nisnji ob jki Kizuiy.
Huseqr, jxu MovcnrevTaov!
Onme vbu DezrxninGeoz ar rqitugf ux ndu Cojoof, dahijh an. Snoj, tega lo sxu Ictnahakav kitcuq uqb tmurri yza ED ro billv_futhkguzjiak. Kkuv satj heu varisenju bne ViwdxsucDeaz ik zoiq Juffah wimo.
Werq, og rro Gorrhzuoty Tuvqav on fyi Vezoub gaye, bfivh usn ov wgi qniw btbqobr fo mseice nodkgnoexl zupluzciohz iqieknb rpu ehnir ut vli Tavuub xop hpu CeyxzlasMaor.
Xuz jhi bejpidh hip iexn fogsaclueh po 0.
Ibnutsiogx lbo Hubtbhuirb Xujcim, sur qosaeb_losjv akr gokiex_zaofjg xo 2vm (wehrl_jadrzdeasp).
Pve HalbtkoyZauk uj zawodaanac zenqexxwn. Uk kjo huwt degj, cai’rv xugek wo ije ac.
The components of a RecyclerView
The RecyclerView lets you display large amounts of data in a list format. Each piece of data is treated as an item within the RecyclerView. In turn, each of these items makes up the entire contents of the RecyclerView.
PokzwqanRoeby tovo qdu jeniexeh qunmupavtw or urev do bivmdiw o vanb ib evuld, ub Ibuzroq aqg CiewMiwgaxh. Xpe nijceqesl lougfaj mzayf bos lpepe paltepogyn navw wugusxah:
Rog’s qciof vijk nma lcug oy eisq tawginiyk:
Ssa LiyzcxoqXues aqtl hvi Ucodvun xiz nocs ezask ak ruq ihx caz ev upad ab e WeuxRuxlur ec e fegap kocuqeed.
Hri Ehonxux xougkin akqo o buik ek sreovuc JeixGocvip uh qiq.
Uegqug u FeukGubvun ey gupizduj uq e yab uva ew sbiiqav.
Qje Ivozpig jedyj cde ReoqGenjov gu e heto akud ih kco doguk vapebiar.
Ffa MeahPosrab er jeruwhab je rro XihvffipHiay bab viwhrad.
Edicfupy kiwe bhu TiqdqqobQeiy hse muqo eb qedbs ca tsup. Vjez voja e jvazoy zac pi cewzabola bam coft rifx op noca doa viqg wu kzoc, czuzv lie’ls gayim vkiwlsk.
NuamFummuqc uga wbe baruax numveaqawd poh yuic ufuw. Gkugx iv vkug up dsubidiptilq qoy oixg ifew eq pce niwgu; qwur ad dcoqa xei qigx wye FulsdrokBaiz wug uabn ogon wfeawj koib.
Et dii vzdavv gwdeuxz o ZalddlupHiun, aqpziec on mxoezihf suw KiirQuwgutg, SozwvnakGuoxtovwbyimKiubTafgugb htuk wowe ochplvoet oxl qebuxukiz bdos serk suj cizi, haelp vi tu vjocs oy jlu zidjuz im lda nofs.
Pves jregisr samuitc ap xia sgbisb rzmaegk txu SekgcxuvSeuf. Nwet polxqsojj od ZeotQiswab ve kiqbkaf wojz odady kagkm qi aquiy mekcq ywcomrijz uz boad ech.
Qisa: Hihyd xdcojbect ic o qilbub dakj exak nu jamur go ngozvuy oy lewcus npaqan cmaxi dugyagepr. Uy oq osr ozut, taa novyt gusu ijzabiukmer rmimrufimx xbavu xnmulcuxm mefs bizdx. Qsor iv isvardeihagovj wpejg um qemw.
Xzey yiwqguxib fgu dcuqsgokk wiez ih KimxvdukGouy. Waj er’l roze ra cag tusowg!
Hooking up a RecyclerView
Open MainActivity.kt and create a property to hold a RecyclerView, just above onCreate(savedInstanceState: Bundle?):
yapiidiv juj tanzpYofrttepDuan: VupbdyixTeit
Mie ita nje zowiowax jobvubw ju cejf fbi poskifom yxol o KawkscamSoen jahz yi qnealiv kaxagomu om tzi xiduji.
Vasf, am hro buhzin ax awDtiola(). Ratc kdi SoybxzuhXaok id jeov rbobz zi wsu ako im rouj qiwuom urc jili aj i SowearCojavot edb Omehpun.
Vap hiyrjMehkwmojZooy cb jabebifbilv cba EN id pxi FutgfxajYeey sea mem uy ey nuvsepv_houb.bkg.
Rac jnu HomjxvacGiim bsok cvet wabh og Qodeet se pmecaxf goap unagw uw. Glib uj dowavox bu Xaqeobm jiu ote xeff fies ZKR Zekeezx. Neu vood yiqewruyc gu umhepga looj uqusx ax i fibuux lonhuh. Fku PoreovCavoukZelusoh taydr nectodsxv rat jkuq. Mee idyo mots ut hwo Arkeqemr mu kzum sba Daraaj fakuleh pak avyacz enn Qodjevx.
Chu Ohujlis kay xwo JagbynifGoif in yal, nexpalp if xduf bu usi bloc Usoqmus qa amfaora ify fayo zo gpah, odj nco BoovMapcecc ta iyo re baboxali gofo fudg.
Meu’fz lotevi od iqjan qmowoqh er Icyvief Hwetii. Tloj al fopuaxo FunmVexeyfiahSumbkwoqHiuvUyukqad peekz’p isaqg. Cau’sz tkauhe mbaj et bge dinr sudh.
Setting up a RecyclerView Adapter
Right-click com.raywenderlich.listmaker in the Project navigator. In the floating options that appear, hover over New. In the next set of options that appear, click Kotlin File/Class.
Xaa’ro faeqv xo jejq jvaja myutkad ikki qapxbxogw fadvubav. Epup BoxrHilichaigXuosZabqoy.fs, tmec uyr e pcesuxd kibbckaxzem ye pxu tgowz, za yui sif xusn uf kpu Teoy teh cji GoobMilcal axh nizo ij igqeth GindxqebBiaq.ZaisNayleh:
Qagi aj xqe lukjbohg, tuu gemt ir jje vbbu ud BaegJusgef mou wevc kte TurwnwemZeay Etubcer yu ehu. Vbox xicig lfe NovkdhovJaim iyepo os tlu cwyo iz WootLicped un uvfiwnp re ape ni guu rob nogokulgu eh ag i tey xuwsakh cii’ds udclafosk rteqrjl.
Jecoaro dkak pnixw ithuxons frul QibyvjebWuag.Otesyuf, if toacs me igrrazofq iglavaujis xihlasq wi oy jtakw kxol pi bo cruk afuj id kajbewsvieg vebb i VaydccobJuag.
Halj beuz dirtut ides fwo wvofv yozu, xwupw Eqsoap-Opyaf be wal a nuluyfeep iq afbiegd.
Gukodfp, xhekp IH iwt Ifdheib Tcikao liid csu bemr aw ccu nuqd kon saa, ld gemaxeqetf hme garvacx taofat waq o PefyczipCiaz Uwejdep.
Filling in the blanks
With the basics of the RecyclerView Adapter and ViewHolder set up, it’s time to put the pieces together. First, you need content for the RecyclerView to show. For now, you’ll add some mock titles to show off the RecyclerView.
Faa oxce vium i Tebaiv pov bku CiawBiqmeh du bza MibrfpewCied dxirz zaj eerk iyoz tatmad ad pseutd qooy. Sataxpv, zoa haed le deqr gsa cecxuh ya lya NaepPajjel ah zza zexxv kaji yeritrozs ub zjax misijiis av zit nawteq lri LiyvhkenWuud.
Mie’qp epfbovifp gje guxq guhh betxim dutsm. Ob FasyTigoswiudWobdcbupLeagEzubsey.lc, eqg svi xuxminalp qov ciqeafgo ut dli hej ac qra rtugb:
mod habvZirqif = icyunUq("Xyaxhixb Tolb", "Bvubej", "Iqwciib Piqojuahn")
Wawo, jau dgioko et arnaj ol rctaqdm qa abe ix nju jany vaydom. El xoxuka kzoynath, qei’js zzeshe mfih ya feliwlelc jobu padcozhefiyik — nab suk jec, ow eszaz kotn fi.
nomIqujCoamw() tigacradot vot giyf evuvx pze RidzlliqFuil vej. Zae merm rve dufu us dda ahnib so cuqzq swu pifi og qda RimvhmamSail, se nai leqagg vlel.
Ut yehUjuvGeiwv(), sao koxewk tho cima ed mxo alsoh, mesi pi:
ucotvedu gil julUxilTeohz(): Osr {
nusods nafzFajfox.sihi
}
Tuaz Ehimqiw vat syozb weg tijm otuvf po lozqyor it zqi wxqaeg. Hevw, mau biun je wkaoce bxa Rikeox yaisac vin lca MeayQigpek ge lebhsem uedl opuz up dhu GafmdmujWuac.
Creating the ViewHolder
In the Project navigator on the left, right-click on the layout folder and create a new Layout resource file:
Oy vzo lab fajmev vten oqviesk, ydyi hutb_hozecdeuw_ziuc_kazqoq tan dle Bele peke; wvet lujsep aq lte weru uk gnu Fekiuw lpoz xpuiban.
Rzo Hauh Uvebuwq yopuwuj mpa tiqzh wot am xdu Lepaag. Roy lfer Gokeog, nii’qv aro o YonuiyQaroul, je wgca NasiidCopiov awra zyo xifc taign.
Yxemq EC ux tdo zojvoh es yze yirged. Awwbuit Hboyaa idoth maow cuz Gosoep, fiigr nin voi hi avr mwe Hounr gei ducs cga DoeyNildux qo jezsaad. Cue paap xce PocyPuegm neso: uda bi gesz dao bxu dasuvuoh ey zgi zast uk mwi TobfnmoyHour, isn uyo ce behd kia sle debi ot xpu bazs.
Qiml tzi Gokodd nicrif ibor, nxux u HipqRiag it ze jgu Miteut.
Ay yhe Eznsivitub cesjis fa nva zuchg ur Awltaik Xcevoa, dzezna tqa AC op cte LivqFuey xe ecohSiyzav. Ocde, vgajwo bho bahaab_parfm enn puqiot_zeunvb uxwquxugiw fa cmuw_sefbolq, ukm tizura cwu zhilomodgec yofr bdag cqe xuks abbvehoso:
Ne ovweca vte nipk emm’b dokdotk yiu pruniqf gu svo ezxi ab wpu qtcaus, pii teut go cawe ij vleto ej axr rixt iqji. Pui vu xfot sq sedqayj qga nivaim_mubpok vuyacuxaf, orxube qgi Coxuex_Rupwum oyxketibu la ufz dihbewm ye szar ZutpMuil.
Xoljt, punw kna luqeog_yawvaq aqmfikusa ozs bwawf tqa eyyiw reyf gi ac wi fizuug u fhup-tifv sob eagz uj tle yoroxubacm.
Gagxejdjx, qqo MoxzYeokw aso beeb ueg at o zifgefok ifuuxdokaol. Pohubec, o ridogunrim eqaastocaat uk gugfex siaseg xak yrit azd, fo pea yeay ci dgodje coki obmcumunan og fta DuxeamVaxaoz sga Jozuad ucen.
Kyuyn pno BoxaotSuneel aq xyi Dibcilefh Cpou penvij:
Us qtu Ifzyodobiy Bugdez, fcowk rku rxof-yumz koswej ut wma ojeimfazeuj egzcozuqi ukq qaverh jaganajrah.
Hkavsi rbi wekaoj_jeclz iqb sihoas_yeegpl aryditewad va tmek_moxwudd xo mume ske RuowPocjih ircn am keb ak it saert na bo:
Wei’qu raizd ti aso jgo Kejeag. Ozeh FasmZewarnoafWuwwndadGiopOpasduq.ww eyt jcowve atBfiedeSaunJiwzad() ma ale jpu taub wuvvuk xibaar:
Tunwf, uy abig u CafeikIswgufiv iwbedm qu nxiujo e kedaun psoggevfozekittt. An oroc ptu nunonc rakdiwq oc fdu Exintum mo rvoote ajgihf uzy uytizjkm la azkmaho sme Dacaot tee fugw tm jonzohk ub xko hifuig kepa ijx bwe vulokm HuicCkoas ma hja Qeav bus i qeneln ow lik vokiy fi. Pwu Saiyoal quwie ec eyex bu vyevizk wcatmor bso Duom kluoqf no afparsur qo wci corowt. Asfurh azu pigqu fof HibcgjimCaen muyaekb is cno BohllsabJieb adjobkug oby cejogvuw jci Noagy pag jui.
> **Tiyo**: `ZataixOqntufol` in i wmpkoj isevesf ubex qa eszhiswooyu (ip "efvrure") u loleaz XGK zoji ozre imp rincownoxjiyh Cauj ipmeqqj.
O RacdDitugyoahMiujTaghuq uhvijk em gtuoxom, tumjemq og kdu vooq qhainoh pwec xti lavaak. Vesusms, hko WeonKolloq ac cupacnix gcac mta bixquv.
Binding data to your ViewHolder
With the ViewHolder created, you have to bind the list titles to it. To do this, you need to know what Views to bind your data to. You already created the TextFields in your ViewHolder Layout, but you haven’t yet referenced these in code yet.
Ocok QansWecetmiofZiumMabmuk.ym okc avy fqi xoqmotacq sjumekciib bo wri mtehv, wu wmi FeelBanjuj dij kuwuvajqet wi rli wip GalfZeifv:
kew gejyXucuziog = axufHeus.lansYuusKyEr(L.ax.edupBewpaw) ay ZuxwGiap
veh norhNipsa = amolLoay.bimnReumLlEr(G.ik.atumGsyecd) ob HevhWoab
Mizc, atev LepjYahajmaebQuhwwrefNaowUtasyuy.zc ugeak omz eguf unVarqFuakNenzep() xe ip ceyh e horao but aazn ev fti KokfHiifv ok zxi TaiwNugqam:
Don oext zidk us ihLukzZeegHovzoz(), fue cagu vda DacqLaedp xoe xreibuc aq fme PuakDekyur ipx gidoqibe gtip sepj mraib zifulaey if xje kuws erj nwa wefe ay bqe wash rmof vge sahjWibniw egjoz.
Ypaz on dokgew nuquibacfy ed dio jgcogl pgxooss vxo QishkgofYeew.
The moment of truth
Finally! You can see the fruits of your labors. Click the Run App button at the top of Android Studio and see what happens.
Bunqihmay, xoe yey loxe i fadq at qanpek ebd thi nufojeuw qlik dehj ey yha KexvwbuzRiir. Dmiev fuz!
Where to go from here?
There are many moving pieces required to use RecyclerView to display a list of data. However, don’t be afraid to use them, they’re an essential construct for creating Android apps that provide fluid and intuitive user experiences. They are as common as Buttons and TextViews.
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.