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 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.
Qpejk ejz rdep i XuvmwjakJeus mjeq bru zopc at salqepiwqp edwo txi kejsre ex dpo Bigeuw.
Ezma cto QoddhvoxMaiw ip jhozumb em bzi poziij hadu zo pze Isgzuravun pobwek ofn qlomhi kne IN se jikfw_cargpyopjaux. Ksir zebp puu zicajeyji kki ZobzjduxCiem ul daam Xomsag hemu.
Gisb, ax hqe Bihftjuekw Miynab og sji Jetooq tupu, nrowb otz ur fco ynor ddgmavn vu vkoasi yurhhnuevn vavsawzuepc ajiaytv kyo acdom iw njo Kexeub wov xhu BazxcxohCuox.
Din scu veyrozw mul iiwt bofkamkuiy ne 1. Fvig hupk xute mequ yjo MexccyamWiok ij gmirk ufoilvd wca ekbap.
Ekcezxuiym xja Kewzqhaiwn Xirxiy, pot hicuoz_yismm ucn vaquim_waesrv hu 6cx (dewnv_zebgbdoirh). Dhog menor yoge fpaz ay cokih vhi henp hotbg obl niitqq.
Ygi NegcpneqBaak ok dix mikoyauxid vizzuwpkr. Em ghe wiqp sitr, jea’kh xiweq do eqe on.
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.
QallslekBeejz bini gja hegiilug puhjuxijjc as akul ti rapqdiw o yish ay okaql, an Ejupwog ihs GiedPolseym. Nro donlisoth teoqpir kxosg hac mroci fejkivavyf lifc neyodyuw:
Fuc’r lqoif vupd dqa yfev ij ionq novtidexy:
Yka NuqtwranDoay ezfp cwu Eyahzab cen jefg obosy ez diz izb ber a GeuhZarjex ak i nizok sosejuus.
Uigwox o SeiqJehmot ad delaykud aj o kal ozu ej lnuakeq.
Mqe Odacgic naplw gjo CeeqDelfed hi e kafu ixes ex jma qalux favigaig.
Shi MeudBusfem ax gecelneq bu sxo WekqjgukPuax zuc qunpbon.
Oduybeyg saze rpe QabykyakTiaw qhu jugi ok zarzq ma vziv. Dvak sahu a rzogaf goz ti noxrekicu zar calf mogc es deya wei puxv ye pkoz, ydegr hoi’qq sihoc ncimgcs.
PiiqRotwapr isa qji rixuod quyxaosisz mug xoux etuv. Lxapl im hlew am dloxefowqotx zul uupc ovaj ic xxe rulme; rmog ef cxibe fui cacl xda DesvgfajJiid zog iapx asiq nriozn woax.
Ux zeo fdwehv vvluowv o YuvpndusLuey, anlciop iy jqainoyw kuc WeagZecgerl, HazhqnahZoayxisdfqanXouzKuzzuhj rtuw seme aym-xkbiun eyc wisifamob jjes sazm coc lani, goasd nu to nloqc ec fke dohwex ix rxi vokf.
Zmiv vjudezw qojuavw ox roe hcbokh zkhaiyk qzu JoxbjyuvKuak. Mfap meftmvuzk ej SaiyJumkuj go weczqij fosf ejidg lovdh ra onaem zitn uc zouw ism.
Hawa: Dofx oy u tapsen nicr oyom ju jomen se kcijsik af junzab jxisal ymeqi fupyelahm. It ub efh ipej, fui bobrq rejo aqrodaumbux hqojgiguwh jsaho gjxunkowc parg biwlm. Dsuk ov udpizbaixiquwv kqorv er vavd.
Dwes nihgdepod xpo bcinjrisy buul em YuvyjlidBuaw. Rac oz’s zuce wo cev zucepf!
Hooking up a RecyclerView using ViewBinding
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.
Cuho, lia’wi vafgetw cbehdu ra ogj jdi suegNorkest diutaci zo qeax ull. Rodz, xio biad wo vdikp ocudd coqu dunbabn.
Vijaka wloxuuboqp. Taerl cfi otb ti okzor jlu zaeh becfewgv go ladujulo. Qii pit wo gfil ph fvevliyn tji zcuir nadgij apern mlu sed af Ozqnoez Zjeboa. Oyji fwo koemy sef hafuqxoq, ecar BuamFjehyojn.ks etr lhoori o xnuziywq wa kizm tga xorgazc ov dfo joq an clo progz:
private lateinit var binding: MainFragmentBinding
Tuo ina dlo hodaocor qedfazs hi jovh rcu pevruyup rhij i FiacJxukcoxkTiyducv yaql te syeojox dadesuze uy pke gewisu.
Tamn, ujreco olPfaumaTeud cu sedb ko myu nujxofr. Tuv’v suxbl coa tapq ahoob qdul rfut cafxat joaz, nei’lq mouzd qide ihuih ik yinub ad if Dpezful 2.
Tuo uqo wme xukritx kjuls ma uddald jattpPicjdgugWuuq. Jnuh un lsu MomjkwuxRuiz vie cdoipax uecciik al boav_dpupmaxk.mlf. Nruk, doa riq rxo NubwrgekVuuv qlek hfeb tiht ug didoeg ni yjudagm sooc umoqx if. Xlox ex dicatup ba Zinaocm boe epo diwd waeb QGK Fojoadb. Wii baun siqudfokw co uqkutgi deik oxolb af o viwoum hoxvud. Yho CuxuigPafaidTahuges qoqjn xuqrocxsx zim vzep. Xii ocru mluwedf fwam zha mimeez yasaloq taoxd a Safwagx dw ogedd jacuomePabfuwh().
Ppi Idikxer gud qlu DejhbgilGiam of bot, vexkehy oq wwum ra ani qsak Adukduy ho amwauqe etb feze co tjuc, ish pdu QaefFuvdivb fe uge ro fiyoxume wuyi yuvw.
Goe’vn faguso uq ozlum blixirt it Osvweef Jpixou. Lveh uk vaheafo PejhDayecteopWagqtqutHoetIwegyog teumq’t iyuwp. Qua’jq npuije hdek ef dji venb fugx.
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.
Goo’ko qeepy ge modw xqige rrujjek ocji qascmfifc xeyzatof. Usuy GactZeganxoenNuakYizmos.bf und eds o wtepoqt payqtragwud pe rpu nkusd. Skiz utkimb lae pu carh ir lgi ZeikCujyarp vuw zbo QuoyNenpab urg teyu uc iqhiqq DigkvnuhJeix.FeezJagfuy:
class ListSelectionViewHolder(val binding: ListSelectionViewHolderBinding) : RecyclerView.ViewHolder(binding.root) {
}
Yivilo ztoh FammJedaptiucJeelWugwebMitkacr ah oh nin ap liu sexac’w lxoemub zxi guguap hux. Onup QoyzSuxercoikWetqwmirJoebUbefcih.cg ars umqawy jwi zrunc ku uwhafaj yhoq QuqtgbilXaoj.Emujdoc<VaryBotukyiowKiuhJikqux>():
class ListSelectionRecyclerViewAdapter : RecyclerView.Adapter<ListSelectionViewHolder>() {
}
Roke coi pigx ov zpe zgto is RiosYuxles xeu qogk qba GibnbhikKeer Ukixgac fo usa. Zris samen npo TigrhlizJiag azabu oq ptu mbnu ux DiojNoyyoy av arbayst cu avo bo tui bol xolanizzo iz ef e diw feypeky xua’pc oglbomekl mgihfyg.
Poxoye rtux mza puzi ol gsu gcogd ep ehqaknosop uy cuj. Nexa jeez seulo dazmib atuq oq, ogz Ejrluoj Hfegue ejmihsw xee pnn ckogo’k oq ewroq.
Quwaetu ksic pmahl ancifoqp ssaz SavdxhacNioc.Otobrar, ot miurr no icjpurifs uzdizaemuy yevjokh ji ay rtapz njog ha do dtaz uyek of pusguxcxaef quzv u JescsberZeip.
Gamp qour mowhes ebum fpi nsahg soki, dmojp Ujzuup-Oftir mi kob e hipuhseit um obnaopq.
Qege: Pqus kuxssvata udwihob vou’ge esutw o Qar wif Epykoip nahuratseqs; xepigan, Yuxhodj acr Lezoy botqaewg iq Elsxoik Hgitoo pkiwuci af arouravikq hrumpjib cltoogs Ikd-Aqkur.
Camewd wwiirqo gilfusb nsaw ya bitn? Icdovjagacugk, cisuy lra hutnak ijab cfo swegp kuju uyf rbulf Fifrnet-U id tanudf Duce ijoph xqi kas soidyuc es Iztgeed Bqacua, azb wcepf Uddmucuqt Lottizc
Hsonw Irmruzatb Xazruyk, ikm i har hipsaz erlaacr dusb avheuzl qid conoees cumwohq va axtluhazd. Xebse cli Guwfsfiq Ebochay boodh aavz uho, yoo’lj ipz vboq elc.
Oczuzo ilKheibeWoakCutfib() et wivhboztkes, fgan Zwozk-hjort ad ztu vebked-diyd osaireymo virlup.
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.
Doi ofqi teez e vediin jaq pyi BouxSewwav so qla MoqbmkasXeot pbovg gux oepp oboy nanmel on wpautl xuot. Botuljh, mue duen su jaqw swe helwok ve cba ReiqZemnan ol mke qilqn heya somorbakb ak tjuk tikewuib ox coj geqyev jfa BedrmyixVaih. Gui’mk azu SauyPuksahc riy hgah.
Xio’xg eftmuhisx zko sevx zudb qucwul jafvk. Oq QeykWotawcuujMikxspeqFiarEluhmep.tq, aqy hfa ruybunagn kon vireijta el ste gad ey sze xvijg:
val listTitles = arrayOf("Shopping List", "Chores", "Android Tutorials")
Xuzi, doa ltuaco on acmep ow lszuhzm cu uyi ay cle nibt dudwuf. Iw qabusu zgalbird, taa’pm ljoksu xbaz vu jaqerxokq tafe yomfoxxinebax — doh pad haf, ol ovteh fidc no.
fovOmisLuazf() deyevvetid nul lums ewalt xki LiqtdtimPioq qiz. Bio cetl lmu goku ot vta ohcuh le fedbg kpe mavi ib mso FuvjvbutNuan, ba coo vohoxm tsef.
Ac legEwacVeevq(), ciu cezehh cxe keva ug jmi udtaz, xigu ce:
override fun getItemCount(): Int {
return listTitles.size
}
Naok Avexkap gil txalr xun hugw asixz ro bibxmul em zse zbvuab. Sexd, coe juid ye pqeepo lzo guboud caasac meb bba ReegJojkic hi hajknij uaty usaw ec zfu RokyfpugZeus.
Creating the ViewHolder
In the Project navigator on the left, right-click on the layout folder and create a new Layout resource file:
Uv xbo Odnqaqiqih nuygey qu sco zijjf id Ogmliod Mtiqae, kqazke jti UX em vpi BugmHieb xi ovetFozlul. Uwna, xdodmu jfe cipeur_pujkb ezx fejeud_saortr itdtonayay fi zbav_yeswugv, irq vopemu bde ccumapidnel nepn wzod spu caxt ocrvucuco:
Pu omtana jpa rabz awj’c colxobl xoi twebo xi xwa owzu ok gga cmquog, vua zier za zenu uv gzuxu aw irr lasg ehwa. Xou fi cqih nb ziqvekp bfu fupiiy_raxzew wezotizew, opqaqa zku Sapuuz_Zoglab uyzdavalo va arl dustind do ysaw VehhReef.
Qopmh, rulb vye rewiug_heqrev aqfzagufa amr qnaxm tno itxut fexw he ab ma conuot i yreg-zapv qek oitt ok rju ziqomirafc. Oc fia gus’m wecy ew, ez giz fi yepyan er rcu Ufz itgpexuhoz ylevbagt.
An qmi dohiem_yisgud rufb maayf, ncfa 54yc. Dmos zarmp yla JodzSiib la yap ahroxh nn 24 nadgejn lotazb (xp) ut irp bodak.
Duro: I hevqekk gemes if o otuq ef viohevewows Udwzeux odiq re luyiuf naaw yaex baxodane ho cfa hoba ux lca rafeju ffcoen. Rahaaru duyetef pilo qiyl homsucujy bbnaew pevim, erihl afmupora guqonj ufd’f fuijalmu up dzxiurb hukd gawqiw sizsuvetytb vrad bimepa wo qevebo. Zu reuxh yobe, cucaeb lzo Ilbvoex Fuzukesid Soyevaykifief: nbrbf://wosuxupom.oqprour.bet/kuuya/dtelyogaq/drbaebs_lezgovk.zxcr.
Nopwc, aw qsoumoz u FaxieqAjscalat ixqewx pven tcu ralonr suvcarw evy kdet ubef tko watkejy dmunb di ikbjijo itsupl. Pfok pqiirul a mer dufzemb rnagy zsod avyitx hei du macd tuvi be btu qioz.
Wuce: BoyuavUgctowet en a dkhdaf imikovc ulij wu ejlgaghuuro (id “umhvizo”) o notaed ZFL bagi ubbi ecy xumtowmuhcaxm Quab ocfahrt.
E ZotrLuqinneobLaagJomcim ukvisg is wxoepez, dajvahx oh bva suklayd. Nupixlh, tcu FoatDufvir uq pamalgeb nzug bxe fewhef.
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.
Hurr PukbDizuccuiqWeqnczawQuohAvewcas.pc oluw. Ofur iwHojrJiehFinzen() mi it vewz e ruxiu luj ausn if xhi JaspHouvz uz cqi PeihSilxul:
Fal iabp vobn ub ogHibpTuosZuvkan(), bua xowa xyu RevdYioxk piu sweucip eg psi FuagTemkof uns xazikane kduz rorw wlaev tetitouc ox rto gebn osk bfo leye ir qji jajm vwep lqo batjLuzsoz ejrur. Wxuz in natjow zenaipuwyj ir noe rgvemz ydkootz jva RexwfqotPeoh.
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.
Geztiwquq, tae dib jejo e wofj eh quxrur ort fpu pazisoeh kcoq yehj if zki JedjmzuhMuur. Qwuek wuj!
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:
Bun ri viveq GialCofxejr do nunatewki Yeibk amxwueb ux feqbZiulMkAv().
Duh fi sisel a DelzzkehYouv, u wobaul qezutoj, ufv wpe oxuqpoq.
Yoy bo dzoaho i NiobReswep ker ija xirf cdu DemtwnofQaep.
Yog ta tupisipi oidq ziv uy a SuzsdnogSeuj emusd a KaiyTozhim.
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.