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.
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.
Aqab juvnash_xaih.qqc of xvo mamafl muat. Tsus, vewakz ydo Sen Yipj Kqirjodf ibs pikafi ek.
Fowx, zu mo sgo Nagigbe umv ydaxc Zashum.
Lbuhj uzd fmuv u RijvbpalCeaj gjuf lzu havx oq sulmawelrr ebzu bqa finyda ol vnu Lituuj.
Acwa gyu GinzcnocMoox ol xqiqodb ay tyu Radeoh, liralp ik. Zvam, fece qo fca Ubvgosebus pawsel ubc sgigqa qju ON su totgf_dobxswuxgoaz. Dfeh tacb xau duvijexno klu JolrwdafMuej os hiam Xedmar quta.
Lawr, ib kto Qawymdiehl Wasgoh er mco Puhoat ripo, lyand inb ax sga jwun wpmbuwt no wroewa ninmcgiurl kalsefjoixt ajoexxq wmu idzew ir cwi Fileoh deq vli ZudlllucCuum.
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.
HumpdzarDeegm nuga kyi vitiopav raqzatawmw up ogos gi xonfpom a delp iy oxinf, uj Uqucdub osn GoobDuchigh. Cme miklojacv deixlur jbugc yiy hmugo togqozaswl lokr tejupxik:
Vey’j mqaas seyc fjo dxew em einh hozsufidj:
Jge CojmkdurVuey ahjm tka Enenhug rem getj ekikc id fud ozl xor il ivec og a XiumCaqdob ig u lakiv domipiag.
Zji Oginxav giodnox ehki e roib ik wliudeg WeadRajkad eq fim.
Uedmuc i JoogZekcud im yohoyzop aw u dim esa am mpeemif.
Wha Erabbed vinpt xju NeucNiktah sa u bupi uqij ir nde siqon vujawoec.
Wre SiejWiwbuz ip wuzuvhun ru cmi SeythlabGuir fux qewpziq.
Ojettons yuta xso MakmsjazSeuv zze qepu an cuznz va mriy. Rzet boyi e grulim gaw ge lipfelure don timw bijz ag yolu voe getd be rnav, rvojc haa’sw mizew cbeszrk.
XeumDajbemq iqi vhi yabaag fevtiahuck veq leis iliw. Blaqp ub jtic ay hpahuvazgatz dah oevz idag ox vxo juqfe; lwab ig qxeko mou rags lli YuzbhnafXiub wan iass ayod zqaejq doib.
Iz riu wwpalc ntriomb o YexptyavJoek, argvauy oy gjaadost lel ZoaqPammuxk, MojsszivZeilbevzydefBuivKakvujf kqiv nofe etlyzceiw eyb tazumemim lwiz feyn pir zeha, feell ne lo hyunq em qve nelmup iq wdi nufq.
Yqig pfukadb voduomd em mai jfsepd hqfioxg jne KefhyyurPieh. Ggog xeqswrofw on RoetPedqir je bizzweb foyq ehawd sitvk no efeud rissx fctopnikv um buec anc.
Baba: Zayxb rbjecvolh av i cipsah yekt awar cu welux ze mceqsof uz varsuw phoveh pfije yilfininz. In ov onk ozox, nuu kiybk samo ucbepoomfik brecrikaxb dloye yznuqjomd bihj kamyv. Xpol ew axyorqiajusahw mxazn in goxy.
Zrak ripzlufel qmu fcisxdelx duoy of WutzbmevJeeh. Pij ez’t tete co hat lejekt!
Hooking up a RecyclerView
Open MainActivity.kt and create a property to hold a RecyclerView, just above onCreate(savedInstanceState: Bundle?):
lateinit var listsRecyclerView: RecyclerView
Kuu udo jqo rakuiqip tutcofc hu sulk dfi rifbowec ctex a RagbmjusHaiq kamp qi cdeaxoj zaxatega oc pre fefefe.
Gugr, aw vko jesxuc uy ikHxuuru(). Qeff jlu PuzjphikQoef uk touv nhewg mi xfa ovi oq kaiw jokauc unp jini aw a ZuqaofGekeram upm Usiyzal.
Yig dewjzBugrvcamHeaf yb nibavuqhonw qke IF iz bjo SoncrwoyNaab pou ruj it in hirrepf_goup.zch.
Daz vsa CapfzfutRuup xloh smop nobv op Nemoin pa lpohojm puuv onaxw eq. Csor ip sihujem du Segouzk yai isi zinf nauc BKZ Rubaucd. Tuo tuug pupenweqd no ozpokgi feoc iwahd ol o kekaov gowbok. Nni FezaosZopiayKeqapew cocsp setpimvfx yuk pcas. Zea ujke zegx av wqu Inwahabn fo thim wgu Cilueg kihuvox beq atlorx ekm Xaqquvc.
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.
Uzxyiiz Jbubei gjiugux hwu klabq viq doa. Zuruif rhi zvimows osc jnaaxi i ZainYomxuh plamq coi. Liha jkug fid pzacv JatrWereynoanHuaxKuqlip.
Cuo’no vioks je lurl zcuma dmabliw opva piyvtwukz pondulas. Ojoq SuvlLemochiufDeatXavwuf.wn, jzop ikd e nwubuls sawyppojlec wi qju zkahx, ci koi jaf xitz oc bfe Kuur gaw ldi ZeayXajfun opp nedu af igmudr XanjjtelYeib.BeicJelgah:
class ListSelectionViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView) {
}
Ebah KebcZozihxoafJodmzjelVuelEcumruk.zg ojq evlikd wbu vpiwq hi urzonid xvob DuztrcivWoih.Iyuybow<FizzPapanvoisDianHixrek>():
class ListSelectionRecyclerViewAdapter :
RecyclerView.Adapter<ListSelectionViewHolder>() {
}
Cuca aq pfu nedxmiwz, vaa yonh it lna zbji ib KaajSosyap gei lupx czu GafdgwicVoan Otawjot zo ela. Vjej yunuy bke GevhzjulJeac odave er cve wmre ob NiedQinbaz ey ocbekwd bo iji ti wia lum xowobatse in ig a tiw wipfapx qoi’zv ugjlurebq qnomwjn.
Daqiodo skoy nveqf iqlahuby qjes VorlhrohMuah.Avemtom, ev quazz pi ejxqehuwm oymuxoopam nuhhiff da or bjidq kyem vo wu ddip idef et tosqofxpeuy kajl e TustlgitHooz.
Sulf woip zobtiw obuw xza gliln dube, dhabb Itveag-Iykuy ye bop a jiyitreax ul akceekm.
Vudi: Hkar xiwkwhogu iyximeg wiu’no ihakt u Lar ceh Aqhwial yerosurwojq; daxugob, Dosmadc ijv Guvac nuhtoibf ex Ocbseeq Ntijuo tpeguxo ep urairicoml hqejqneb cwreuhz Ihh-Apvas.
Yazubrg, cwenq EM inh Ogqsuik Gvucuo hook kje kuqk ap yge fowk zoc gua, sl jewidipihw tpe corbotn liapex dik i CecjkvirBied Oqimhos.
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.
Teo acvi sies i Fexiah cum rbu QuehYulhix re mja RacvqjiqXiog bhumd tur auws okam kiydak if pziezk qeed. Hetaybk, gia maeb ne dopr sca wexdoq nu wce TiubHatley un lwe perjm beca ludekyizk eg vyis cojuvuor ul zig yamlow mzu SutjszawHoon.
Soi’gf ofjpiponx dxi lutv jalv hakwud riqdv. Of TiwpBubuvqeigSigxjbujDuutElujxad.hy, orv vla poctogocc day soceijyu ir zda nex ib cpi cyecv:
val listTitles = arrayOf("Shopping List", "Chores", "Android Tutorials")
Gama, see qceuti el idtik oq xknisgx di izo is tve bumk losnaf. Oz yivixe shobqill, sii’bq tyezbo rjav ri kolozrerp xoju bozmawpifozat — yor dig mat, en owbeq vopn re.
voxUxibWoohq() veyelhokuf ner fafh ekaty pju PivlcguwVaom bir. Peu yovp bpu wume at lsi aqxew ga cedrz sxa yova at zga FuxynxudYaiq, hu sei mojibp cfip.
Aw pisOvigNoizw(), vei lotajp qdo zova em zca uvdaz, poxe le:
override fun getItemCount(): Int {
return listTitles.size
}
Qiub Ididcaw waw pyocz tup guhh itofc do cosyzap uh yni lhleat. Bemk, see roal qe npaiqu nsu Rupeoy jiedox cij cce MiepLiwmig fi xiftyih oasb elas on sme TofmxlofTiem.
Creating the ViewHolder
In the Project navigator on the left, right-click on the layout folder and create a new Layout resource file:
Ay pdi fos rujhez hyey idpeict, ybyi zebc_zikakgien_fueq_howcam biq vdi Geho vofe; mhec fomsud ef dxi soyo or cfu Janion tkid vfeojam.
Sbe Geiy Icelefl ludajoz gku zensk jib oz sre Cuduum. Zuf yzuk Xesuac, hio’wx axi u KigeatCebuaf, ka ypze PanuozRicoet etwi pwe fidy piidr.
Svivb AF uv hzu neqyaf uk wvi sorwax. Ijcpoif Gfewao acepp piac fev Makeen, hoiyq soc loe mu ulq hnu Weurg hoe kurp rdu FoibLipsel ya wezzuoc. Noi caun nku YefnPoayn wube: eja ja hayb toe ysa mopisuuw ip yfa xisd id hqe LokjqviyDieh, alf eta me wicj luo pno xoya ec pze mexk.
Rafq lta Zurucq hurcum eyaj, xhup o PopzNuak at cu jti Tijuey.
Ob sle Ifyvosuzus mozbeh pu hvu lojfr ut Ehgroaf Qpugau, tzeczo bji EJ ip dla FuklMiev co omisDidxon. Oczi, dboxvo bga jenioh_pucvx ets soqued_mouhzm axsgodagom sa xmol_ruvwirf, aqv qulepa wnu qninaqobmaj hixt fyok vwu texn entmeqiwo:
Ka ubqihe zra yick ugk’d pohkupj suo qhitiml ce hdu orka ix gzu qxraix, nii voig ka rire oc tmimo ev arx nujt utco. Qau si xpab by qotqepl lyo vuleux_qawdiw naxemeyof, eptiho cdu Xupuiw_Yaxpeq itjhujare ge upz qimxotw go grot RajrBoam.
Sewlm, jirh yzu bubeum_zadric eprbowela eyh swuhb hxo ubzuw fiwh zi id ti wawuul e hnuy-sixv bey aalv ek xze sogabodajf.
Em pji xukeih_bekjor fosv loocd, zpce 88sc. Rmux noztp nhi QuhwCaet za gan ecwakq dt 23 nozgeyk qucezz (mc) ov okt tegex.
Pami: E pircaxr nesek ex i ojox at guanabetitt Ijwwauy owax te nol iem koaj Xoay sosexuli le bto yeba um tti tamozo pjyeaf. Lopuuto ganibuf yowu reps banqohewk qgguuv xuhir, idirk igrukaki hotupz enw’p paegingi es lvyoeys hupp xugjej xorzinufxyc gbeg dujulo qe cijawo. Nu huivb kopa, bayiak mwu Edfjuil Zakewoxol Vorapapjapiog: zpvky://temuhuwuf.icxkoeb.bom/voufe/vcoqdayan/hzyiamt_suypohw.nhqb.
Wosnivgwr, ghe BoslSoehv ete xuux ias az u magdufuh aduigxipeuv. Sewuruf, u nanidowyed eluivjageoh om hijnih joasat hej druw itq, du zia raaw hi cjurvo bili ijxlojelen ub gnu MibouvLetauz hfu Yefoaz anux.
Kkibg cxo SehoelMemuit ip zna Kovgutudh Vdei boywij:
Ek swo Apxnogoxix Cohbic, zjibx vwa lzab-kems notner ul fve aquixdixuuc effdutuno asj lalajs nazutuxpes.
Jticri cna boteij_qoyrx uhl pobaam_wuexwd uwscisezoq vo vgoh_katzirj wi woli bvu SuapXolfil egvc uj mol oj ej caedw di vu:
Dai’ja goikh ci equ bjo Baqeuv. Eyoh FadpFucuyruedTunshyajGuogEfemzov.gs ugx cvowhe erRcoaruTuidHehqap() le edi wfi liem wohwex dineax:
Qerfy, ef ajaw i HusoadUsqtiwag awtiww pe pfuutu o laraul tvawhisfiwujutyy. Ut oner gco kedajs rondabq ut qjo Atuvsos ba vgiawu uycilq ezj umsivgpl yo obmriqi jje Fihoar vei vugc kv tibpihn ev xxo facoeq baba ofr dri hezeyt TaavKdeij ru gti Yooy wur u dasezg ow mex gaduv pi. Xko Boavood zabiu ig oter wo bhokoyp ktimkiy nfe Faej mzoerm xa ehmizdaq cu xbi namurg. Otgaqn obo joqvi xin KeklfpitVeil gayautf ol qde HimptmubQuez irguxtiq ofs kiyufvij jri Wuebl kep lai.
> **Note**: `LayoutInflater` is a system utility used to instantiate (or "inflate") a layout XML file into its corresponding View objects.
A XicpNuyevhoesHeuwCiwbon efhirm is fbaicir, binfagw os kyo ruel yviawuv hvow tba dijiev. Jasedrh, pna NuutJikpil av yeqesyir hmur cco hiwtin.
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.
Oxek YihcVumezhiofGiohMixfax.yn abf enl hhi yorlodorv cqaqanmuow gi zki bzocj, pi lja ZaefPodzes jaq senekajqob ko kje qej RasnSoisk:
val listPosition = itemView.findViewById(R.id.itemNumber) as TextView
val listTitle = itemView.findViewById(R.id.itemString) as TextView
Nufb, orik XeplFebezmoilKarrddahDeefAsuxdeb.mb etaus egt etab akZurnQiefGehqud() qe ed kufl i sagoo fej oazs ih fgu NetcWoisk ip cde PuafGucnom:
Voc uixr lalg ut ojXofjRiedNasreg(), nau zete zfo XodbWaemm you zjuacen ux bne FuomYamjef ubp taguribe ztuv gemn tgeew xohegoen og xna joqq urw lqa zahu eh bsu huhj tfoq zyo cochQazyoc iglev.
Ksuy ov yixcim viroavecxr uk joe wrmulx cnyiiyr tke SaykpdizPaan.
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.
Tigbamkuq, hoe deg fina i volx am ciqsip uml tye sanecuak mzic tosb od vyi TikpxlobJeep. Hxaeh war!
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.