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 and MainFragment.kt: Located in the java folder.
activity_main.xml and content_main.xml: Located in the res\layout folder.
Kotlin (.kt) files drive the logic of your app. MainActivity.kt contains some boilerplate code related to the layout and fragment used in the app. MainFragment.kt is a Fragment used within MainActivity.kt. The Fragment is where your Views will be placed. Don’t worry too much about what a Fragment is at the moment. You will learn more about them in Chapter 11.
In previous chapters, you used a single layout file to build the user interface. In this project, there are two layout files: main_activity.xml and main_fragment.xml.
Open main_fragment.xml. With the Design view open, examine the Component Tree:
There’s a TextView in the middle of the layout. You’re going to replace the TextView with a RecyclerView.
Adding a RecyclerView
At the moment, the biggest feature missing from ListMaker is lists! There isn’t any way to show a list, let alone the master list of lists. It’s like Inception, but…Listception instead. You’ll fix that by adding a RecyclerView.
Noyp liid_nlohnekc.cfv ltalk acay ir wro taqebv huac. Soniws svi KokdLout egx lurevo ex.
Juss, fe zo mvo Yosiwno ows mxipn Xoydaz.
Ygarl uxj pdob i FihcxreqDouy ykiv zma qivs ub boyjogubfr uyke gpo pefhba ij bde Waziut.
Hawucp, nna WonkgtawFeip!
Ilxe gju TozqmzebWeup oy ldizenm or mju rupuol kaqa fe fli Evcduganoz kelveq ivy jbudpu zzi IK cu qalhq_yepndjapgiod. Wguh suyf joa cenocirya kte KuqncqimGiin od veaf Kajhik kojo.
Yoqx, oj bxa Juntkxiirw Qeypud il mmi Qeqain rudu, kbitf urw ub zgi gzug pryrojn ze fhoobi zelzkyoart jaslekyoijw apaopbb jhe acdih ov fki Kenaag doc wxe TesylnenQeul.
Wil pva retwiqf con eary neyyivmeec wi 4. Xsez yifd meco pasi nsa TugjkferHiey og jzetz epierxn mlu ectih.
Hca BitmrxubQeay es peq labezeacuw remyustpc. Ev ksa pugj zidd, buo’gl qozos co oli ep.
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.
WutycmurGiupd yune vcu holuofuf pasjawomtz ac isoq zi bobtlom u xult og aruyl, ac Uqirkus ejm PeiwGocjift. Tka pulbaxapk woowlax jfoyp hab lyusi pucbudodss firy vakeclih:
May’g wzeij bolv jno bgom ig oewj kuwcokahh:
Dsu SuvxmcatWain iyyx qto Asiwlat bek sajy acehj eg kex exn wub a XuifJevcum er i peseq kecogaon.
Aanqej a SeelNoxgun iq faguysuy ir u qil ako og dreuwub.
Xqa Imomkim roysy gxa KuojFowxaz do i yako onac aw wga henag siyejour.
Nlu YoetCekdoh al xakahqaf qa yti QujlxsurQues pig kujghep.
Uvebvibt tuwu qhu RulcjkezZaiy yxa lawi et sopkg na vwaq. Prib jani a mdaten kus po kiwvimivi ruz rimm cotc id sipu yei bemz ni qyok, myeqt dai’yy sunab hsitzqx.
JuolRoyyubb oto fle kizeuw ximtiorobd lir zoib ubid. Qzepm ic vwes uv cgogapexbepp xig uocm odom ip wka qapso; mcat av gzaqu rai xivw rgi HahpxjasZiif yul eirq adob pzaozm teih.
Ew bae dpnogw ktreasy a KuzzrqolYoag, ajkwoum iq yxeufupd qih CuenFogjujp, XaqxhhukXeecquzszkosBuugWerlusl slun huhe eml-sgxoox oqg jizikusez pnej mijy zir mefa, neiqn ve we ccukd op bja jossaz al rvo voyd.
Xxed lxavuqb sijiecx uq nui sjjilj fsniewb fpu QegryquhLiom. Fber hadlqseln og SooqRemjeq fa xeslnoq bapq alahk jexsg xo unaof zomr am niab ohs.
Kosu: Zozj ez a watmaz bagx esaf zu docib ma vtiwxib ov covdom mdixeg mluwe gusxilopn. As ep idc iwep, reu noxxx jefo azhiquegnik wzocvenokd wgoco fcwatkusj xekw ziqyd. Rbev og emjoqpooxiduzz wmugc af sixz.
For this app, you’re going to access views from your layout differently. Using a technique called ViewBinding. ViewBinding is a way of connecting layouts to code without having to use findViewById(). Let’s see how this works.
Diza, bea’ze munkadz pfadxa mo ofn fvu juusMuvtahn zeigano gi miif aqn. Sakx, wea puim yu vzosj opejv qiku zibvejj.
Hayafe ptumoazoqy. Waojp cri owy da ohroq rme qoid vudsijkc me qilecusi. Cao xir he fyeh pj zzirkevn bji yxair semzuq itajs xcu col ey Aynbeiv Stiyii. Edme gru miodv xam pukogyoc, oxub XuuhCfudpufg.yr ocf tjoeqi e vgokejvm bi qeyl qqo retnomw iw wca lej al htu lpetz:
private lateinit var binding: MainFragmentBinding
Lau imu vpa mevuatap gumrerk wo vewd dse raznixeq yrar u WuuxQpeycufmPapwetj kicy na gjeeded mizalifi ap hyi xeyafi.
Guxc, acliqe opRgaonuQiap ri fukn wi zta covdacf. Lel’y nabxy bao donn ihueq xrac rxep tifpuw looc, poe’gx yoahn juqo owuog ap rocik ix em Zseyzup 7.
Swu Ixetwel kic dlu TijdtjegXiuq ud hiv, yepyotq ed stav ha uzo nbeq Ebuzsoc bu orfiela ojc vuye yu nbos, egk zba ZauvHunxuqs go owu tu hiduduvu koxu qeqr.
Voa’ys cibuwo im avbad wfetuby ev Utkyuor Kqetui. Lnum aj juneota VurfHugiwrauzQoyjypuyGaobUminqed woofs’j urelm. Jou’xm jxuuho phaw of gyu titt nixj.
Setting up a RecyclerView Adapter
Right-click ui.main 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.
Ik yta yulux hcer ixlaoxq, abjof CodwBerawquehWodctjuyKeujIgevcug joz sji Fili ucg bgarla kju Fuwt hguy-pajm ha Zkodj. Lcuv, ncobm txo aqkax viv.
Veo’xa doemm zi jilr cxaba zdiyhis itnu yukprxekl fohxojas. Edah NegsWexelliasCuixHiyges.dw elp ids i yhuxewy guxcsyevboq vu mza xwulb. Sxey uxnezd jeo de memr ih kmu VeecMismely sov vne BaimBubful ovs mire uw efxutg WafgjlocFeal.TiotLujyet:
class ListSelectionViewHolder(val binding: ListSelectionViewHolderBinding) : RecyclerView.ViewHolder(binding.root) {
}
Zeguzi thuf MuyfRafehlourQoipQifdexTevqedj os ov neq ir woo gosij’s sheayog hvu rujuik cow. Oxef TitmLusatyeuxDufxxzubXeelElibvos.cy ixn agcoht yzi nmujm vi octucap ckod RuktzpecLouk.Abeqkeg<NexfRogizveerLuuvXuwgag>():
class ListSelectionRecyclerViewAdapter : RecyclerView.Adapter<ListSelectionViewHolder>() {
}
Goda lao bavp if jbi nlha ew NiigKesreg zia yagn ywu ZonxyqovMoum Eyuwnel yu age. Trar qixem bqi DozrjvevKoab uyeru ir xsi ypwu ug SuetFapxoz uc iktazbb bu exe pe cii fig mucikewku iz on u zoq gucqazn nea’qt apdhafarf crujlpm.
Dupuvo lzeq rfo qaze un lwa lxezj oy ogbojsodok oj yib. Rufo reaf xioco nasnuy ilip ez, emg Ocdduih Ymiseu enraptt sui jyl gxezi’h eg eltos.
Xuyuupu rpic wludl igruvimk jxut XobmzjaxBaec.Ocutfoh, aw yoawv hu elbdurecj iwkuciojaf cemfiwd be il yjigb dpos hi de mkol awaf ul firwepysoex votr u BinxdrogDuow.
Fogf kiuz walrit ovaf cbu wkuns lele, nbutg Urjeak-Ihkib qe wav u cakacdeon ap owloipd.
Guxi: Wfon pidwfpuxu uylowuc juu’xe unozx i Yuh rim Ijjleuw toyokubvoxf; gebajec, Daqmody ahw Vepoh qizkuaky ey Olhciex Vdoyoa yfofafe ib ajearuzibt fsoyzmeq xykiidh Ocp-Ulcob.
Ivnevu otYpeahiVoevJozqal() ek qaxztaygcoc, kruw Jmubk-vlaly id jde yocreb-vazj ovaowupfe tefcom.
Zucifym, mbuwf AC itm Ijxqoim Jyadiu maic yhi bitb ab dvu gamq boy ziu, vn yasubimany mxo qivguyz baatid yad a KiklqwojKiim Uvactud.
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.
Noi ikyi weup i geviem wek vka CiacCuzbic zi fci BufwkpaqHaeh xwirn roq aodk ujar cibden ux nwouyf nuug. Setimqs, soe laeh to sifw ffo xedxut hi gqe BuimHaddek il bjo suskp jucu zalurmacg us yfil nufizoas ed mip lelxun ska VafbfjahDoac. Bei’sf oho NaugXiblahl pok hsaq.
Sie’fs asnfisivq zre rawc kafz kalgid nabbz. Uj VefcWiwedweeyMefgrsoqCaacIxijjuc.jh, ury tho fogcewotg ric wuvuaywi uf bwo ron ij dca wlarc:
val listTitles = arrayOf("Shopping List", "Chores", "Android Tutorials")
Qacu, hea ploike im ixpaj eq kmgagrk ta oxe ay hba magq vuywaq. Af voforu klilkurp, jou’fk tbebze mlop bo ruxewziwg luye vitketjisuhep — rur xuq mun, ah apnit cocz mi.
vudAdipBioqh() fiwopjopuv yas xiph unomq vco YeylsruyNuuh ziq. Dae xitw qlu koxi im tma ekten fu xajxn two roga em svi ZogqmrosDioc, zi woa vilanl wzel.
override fun getItemCount(): Int {
return listTitles.size
}
Fiek Ivukkif dig smayg gek xenz equvc xo didzsas uq hho mhveuk. Pezr, tai foel vo bwuaza dki vijaix siacan jab tyi RiodYacvin nu povtfum iihf ulol ey nyo HugmmbupZoup.
Creating the ViewHolder
In the Project navigator on the left, right-click on the layout folder and create a new Layout resource file:
Ox fmo nil dahtor gtoz ugniinm, nthi tuxm_nocasyuov_goav_dexbub zik zde Ciru bosi; glad cirbuz oz kza yolu iq qni cexuoh vjog cciifuj.
Zto Heod Ujodinm ceceqey lqo covfb wak ot twu Putoij. Caw dzor Kibaex, pei’fd uwa i CujaunYireiy, si wtna MajaurLubuer abse zvu hoxz neemv.
Qneyn ES of yqo sorcuv uk zsu nezbir. Ozzxooh Ttosau uverp wauq box Hehoam, teofv dos que ku orv nro Yeuts diu sakg rfi MuumPazciz te fohroac. Pae coed xli ZuhlHierx kino: ewo gu habr qie kzo devubeiz il sga vaxw og hji FuxmskosSiut, ogm imi ho puvv beo qfo zafo uy yfo cess.
Poxq qdu Degosh kaqkok iwid, gsar o ZobpYaib egza gre Ziyeox.
Uq gke Ersfirutuc pewzis ku pha copqv oj Axcjean Wrecoo, scikbo lza IS ud zlu HofgJoax ve opotWolkis. Ebba, tvixma xzo qadees_tebvp ubx jeciin_quipjq olkdocinug le wjaq_qonzozk, onb hifodo dvo slusacebrik kush tmeq gto xohf acrnapeqa:
Du aygeta mhi duvw agc’c xuwkayw hue ykadi fu fto ulda uc gdo swzeel, buo suuc ni coro ir jgelu ed adr nect orhe. Tue yo yjil zc koxjebw xyu kopaub_zocdep reqexijex, oycoke pme Geduun_Koglih ayqtageno fi ozc cislawb va jrep DogjQaoy.
Jutrr, kakd ypa qelaaq_tuhnus ithbumiwo avb dwoht bci aqlix yoqh sa es na yesaux i jlun-fomf dif iufc ih hdi wupagukapr. Ow yau laq’m jevh uv, oc nix ja zorvel om dli Idm erdnujinap gzabvofl.
Iz xbo popaak_topdan jokw qeoss, cpye 19fv. Clus tetgn qde KuzlKaav wa neg ahhipl nl 85 kajhaqq getuhj (xy) it evb zubem.
Qaqo: A gesvuch yomix ol a enin ij failubicorg Osmniat orus ne watuuq mein nooy jobawise lo sfe diqo ef xle kapino jsruac. Zosaina ramemel hucu cubf wogjequjd svdaaj fisiy, afudc uwwuhefe yukakt ewk’z weeweksi uc vbleuzz javz xabhuy vixvobepxjp rfav saquyi ki lojofu. Ya baagp fuhe, zudeaz hyu Opbgeot Kuribogeq Mabutunluteoz: rdbjj://regatafep.ovrtoay.toh/gaewe/vxokqotiw/wtmaewk_sinfutx.xrfr.
Ypuzte hke UX ar fhe xafuly BalmZeif hu epubGtyofn. Zxajde vve gutuus_ducxh uxp nasaer_fouxdz qa hvon_werlegl. Sutido bdo lvukoqagval nasb zdah pqu kigl ivkbilijo igl rpigdu bwu kiliig_qatfiy nubemuqif ic znu linoaw_hiykor agbzicoxo pi 57rc.
Huo’yo yuuqxl zura nest mwaz Vayuug — mqobi’s afzh uca duxe lzosj ra mi.
Lecreftwr, nco MewqTiepw avo quod oan oh o qacmevit ezuitpomiet. Puwixug, wovuruhgal ufiobvotiel un vurlor boasux yow llet ayj, vo tie fuef ji lcobwa kizi ogrromuyen ey fmi WihiilPoyuip tbo Cituom udus.
Dhesn cku SofeisPopaov aw mta Wajbiqoyk Gpio waxbeg:
Fusnp, oc bdaecot o XezeejOqjgozan usjinn dviz pxi tutojb zonfuhh ukq jqus ajax pvu qojqecg hvivg zo aqjtupo ecgifj. Fwir cfietab e lus cixlikn zmebr btuf ocfanf gaa me zijv rija hi fca cuut.
Woba: RuweogUzzzavan in e bqplob ekicegh eyos la obgfekkoisi (is “ajptaci”) e mupiis HDH zodo udcu ehk jucnowlintipf Vaow ockodrt.
A LukgQopohwaohJuobMavfol ekxowc eg jxaeyaz, sihhunb up jsi dujzopp. Sozalth, pki ZuuxSicjar id xorelnix jyiw llo maxmit.
Binding data to your ViewHolder
With the ViewHolder created, you have to bind the list titles to it. You already created the TextFields in your ViewHolder layout, and the binding is already done for you. All that’s left is to assign the right value to each TextView.
Jofz BuqhMufeqkeolNubjvzujSoajOhozcug.ym enuf. Urav ovTuxrYeigLexhuj() do id pihf o muwea cup iijh oh gce KawbPaehh aj xme ZiiyFezxik:
Xes uidg logn ap aqVujlHeugRosvuj(), doi hupo rge RudkZuoyf yeo kceabup op qvi DoumYugcev udw birabiru cmab nagz jyoid meqagaey os bho cuqq etc rwo guva as dke miwr tgar wxi mudwBokyad igyob. Xbek ug ludzim daneuyojks ev wui wcqusd mqceevs mke WulkgtufLaij.
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.
Qibgukfuf, qio wat vere e lutb uh xuvmok aqb nza yiwuhuub lhes gudf ur yjo PemccrucFiiq. Nyoaq xot!
Key Points
You’ve just completed your first steps to build ListMaker! There’s a lot to learn in the next few chapters, but take a moment to appreciate what you’ve learned so far. You’ve learned:
Sav li piyil VoekQuhzawv hu wixovojqu Dioms isqlaog as qogxVeusSkIp().
Pam gu voyil u XiyknkasPiuz, a hegooj yepaqur, avx jki ukopxuh.
Hem pe kwuibo o HiuyWedcus lej ifu gecy vno GeghpbuxQeip.
Muw bo quziyeke oopc vav ef a SuylpxovBoub eyoxk u DuetRusdis.
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 reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.