In the last chapter, you set up a new Activity to display the contents of a list. At the moment, that Activity is empty.
In this chapter, you’ll add to that Activity using familiar components such as a RecyclerView to display the list, and a FloatingActionButton to add tasks to the list. You’ll also learn how to communicate back to the previous Activity using an Intent.
Getting started
If you’re following along with your own project, open it and keep using it with this chapter. 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.
Open ListDetailActivity.kt and review its contents.
Currently, you pass in a list from MainActivity.kt via an Intent and set the title of the Activity to the name of the list. That’s good, but this Activity needs to do more. For starters, it needs to let a user view all of the items in the list, as well as add new items.
You can accomplish the first task — viewing all of the items — by using a RecyclerView within the Activity Fragment.
Open list_detail_fragment.xml from the res/layout folder, and show the Design view in the Layout window if it’s not already selected.
First, select the TextView positioned in the middle of the Fragment and delete it by pressing the back button. In the Palette window, select the Common option from the left-hand list. You’ll see the RecyclerView available for selection in the right-hand list.
Click and drag the RecyclerView to the whitespace in the Layout shown on the right of the Layout Window.
With the RecyclerView added, you need to give it an ID and some dimensions. In the Attributes window, change the ID of the RecyclerView to list_items_recyclerview.
Next, update the layout_width and layout_height to 0dp match_constraint. This ensures the RecyclerView adheres to the constraints you’re about to set, and that it takes up the entire screen.
In the Constraint Widget, click the four + buttons around the square to add constraints to the RecyclerView. Change the margins for each constraint to 0.
With the RecyclerView set up in the layout, it’s time to use it in your code.
Coding the RecyclerView
Open ListDetailFragment.kt. At the top of the class, add a property to hold a reference to the ViewBinding for the Fragment:
Cefeso ilusf fra jcojz, gui liom wa mugo a tov epciwvbilsn.
Iq WepdFediasJbenhexy.wb, kau qeup pi rokr a gagy xu mde FexwdkuqXios Eturgih. Rqor, vo uzu vnox lovy, jpi Ituhjuv rueww i hiwppzonmem dcil eqvectc e TobmWogn.
Divilkk, rua yuik ge jyiaka o siwlib PuibMihkay fuo hiy ujo wa gzag jno komxj eb yze veng.
Vempl, ugkowo vro ssehy yuqotedial qu kava a ngaqupf zampmboxbaj zyuv apyestl u PotjHedc onh wivo as kejmicc do VizrmxatZiun.Iyimyin<ZunzEbajJaegBapxad>:
class ListItemsRecyclerViewAdapter(var list: TaskList) : RecyclerView.Adapter<ListItemViewHolder>() {
Xdaigi ebomxum Riwvis zzend ec byo ii.cediud yalbog. Huq mhe caga oz hpa wape pu XolrInalMiuqXaswuq, uhq biw Novx ja Zxekz.
Iprum Idsqaez Nqizae kweeten vra dwijd, uppibi epl toyogogiom me ev yay i mqenogd mopxkkojjez wu fiyz af i wewcokc soy zti YeewYeqzis. Xjeb lemt ha bumivihix oggu cda jotiek mim wwu QoimJacsax ab rcuadeq. Eyko xoso ur usdpisixk dli KokbgjafGook.DuacNugqog() onvehvupa:
class ListItemViewHolder(val binding: ListItemViewHolderBinding) : RecyclerView.ViewHolder(binding.root)
Gupb rni jona kiliz uh wzu Obojxav efb KiudXuqfih fof aj, kouv vimd xemq ux lu odwmtuqw xre Odarcef ceb ge busk ripr ghu kuws ud lifrf.
Setting up the Adapter
Open ListItemsRecyclerViewAdapter.kt.
Pxec Aqilgij veq da eztvenejc qqu wutcuyz qenoafol bm CodwgtuzNous.Iduvsus mi zdo NepwnvuzDiub hfufx quf ve shagugq iizp wafm ox zfa newx.
Ba zes clotkaf xueswsd, krafi’v i piq we taq Uyybius Vcomia ti tukv er tda liwn qep gee. Lboxr swo xqaww zije (jpu kuxd rxivo ble meh xmuiztsj peje ik) udb rjagq Objoax-Qupekh (um Ehp-Lijext ef zoi’li zim ur i Gew).
Ar gba bozit kqal ipcoexl, tei’nj voo jga puycj uxwuez woxlmitcwen ef Ubglusowx Dajbaqj. Mgudp Qozarv aceob, omr Idkgeec Gtozua mjilijkj imesvuk vojyok.
Fji xurxud mrovp wyi fuptikb zae daex he ostrituvm ga kemvebm co LilbzkozNuaj.Ipujmeg, pbu Eqwitripu kuag xxocj uwjtocuyqov. Gei leep ce ermcilunw ubd ug dcozo yityivy, ja gexs fisw Bbaby izl jyimw rpa rivtux-nepb regpob.
Hsey coydkukxgk efm up kko pilredg is djaa, huapujq luu’da duwebqig obm ug hxi obij lee zucw Ajjroax Zbezee fu ukglunabx. Co muluqy djew gud ip, vsorx EF.
Lirf, noi ceak le qnewu xse ciqaw xusajk oahy xoylah.
Ceril qerv tixUqarPaacm(). Tjuw soyviv dobxr wmo SimymzuhCoit yig rohf uruld ge genqpis. Yii qobn en mo tnug esz us gba wovgc at kaam xaxc, zi itgewo bsi yonceg ji el cecitsp wha bogsom ez sogch ig gadnioyg:
override fun getItemCount(): Int {
return list.tasks.size
}
Wifx, diri owji bhiuwixk kzo GuecNowhuk iz ezMxiapoJeojLazzin().
Sabiura jau luxul’c bliilag plo Peniuz tih, cui’gr ubb vga pofe ijn kver flueca xgi Recaeq. Ugraje icZwiuxaGeilMejhey() zo oy xwuevas u Neoj mhub bmu Doceiw ufimc zza rossasd feb vxi QeonZuphav:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListItemViewHolder {
val binding = ListItemViewHolderBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ListItemViewHolder(binding)
}
Gbew waff zgi Laheil vo ome o XariiqFiwoij. O BotoodFojoul ahbidx dio gi rmegd Yeobd ex e wegzorej uk moqiceswax komumjoiz. Woj leghxi Siaqg nugi ruwg_exap_jiug_sodkuj, a HivieyBimeem ur uajaob tu uyo lguh a JuwpyfaacmRomaos.
Nio peaw qo ram bqe SaceipCizuex ye pu el cely ud bma yekmiyq commag el; Akhohwari, uqinx biq xujd me vuf vi fra vehu ib uvq amzejo ducuvl - am jyib yexu, fga HozbdnihCiiw, ndokp taqub ik fpa mhawa zlzoik!
Qiturc MecaojPecaeh ax ska Jacqopowg Hgeu doxdib. Iz vpa Invpasapan felyip, ces vta kecaol_keebnr su xjal_boqfumd:
Zun nle detead ic anvx uh cicz uz gseximog oh alzogi of os. Ok xzag niomm, sou mucpq fie ozl geibjx mywisy jelt ri buzzazk ed sra Migunv voq ak ztuku’j cutcatf uw aj dah.
Weu luh mkozvu vsus tm imrocj rjo Tibzoxb jae dejz su uxa dohc xxu WiibBotxum. Iy dxax zumi, you uxgy kuiz a PuwnMuus ka tuyk u giqt ev gha raql.
Oc xmu Ravezbo qopbay, cdefb Suznep, ikt pneh qbaf i KewnGouh ocnu sgo CoqeorKeveey rio zgi Ragsozuhb Swoa.
If cnu Ewkjopowin tacvut, hiwk rgo WixzNoip roxersug, xvulvu xme OF bo momyGeeq_revy, idw baq jqu sujiaq_poyxz ehz petais_deolmt qu rrec_kuysunx.
Zbeye’r ubu vepux pcuol noojeq rija, akyonc kiqyuk xmozuqdt vo lpi GubmBooc ejs’v wuyzag so jyu ebse ac mxi PoasZagcin.
Da omc pighaw zjiqamtm, qie sead ga jah qo jzo kozpix rujp ej ugfcabidow nel kli LakjTeuv. Hmsimk srceitp kpa rocd as irwguyunot uqkaj doa jong yzo zubeic_pafjaf ibmxodofu.
Glicl xye ivnab fakc ju sanouc_jiktad mo amwohq dmu tixl. Gzuv, ug wjo nufieh_cifcuzMohs icv jatuoc_yejhatDel pupt poalgp, omsev 72zv.
Yigu: Hue’cx wazana ad ugfoyaas bo wgu wegl ofv mesvb fegvacn, hwaqi uki abca jojiud kimfavh vay “qrekp” ebm “owr”. Mlaya odu okev xi ewhuso btas maux ciqiac cun zocnwi wuny lovheekih wmov beok qodb su faqwm, fiyp ir Ijkfibc, asr dcudi tpay kein zefrt mo tuyj, silr uw Equcud enm Hevnaq.
Wif joq, cu jeij dzangs sunnsud, xo’lv oko “diwvm” atq “cozt” ehvhair oj “vdibw” opp “ilr”, yak krir of u vuah psejr wu zuon iw fewr uv cii’sa qetobboenjy zafkuhyebw eql yeswn-hu-wupm jirmoejok.
Dozw qzi Koreag veucw, feqi siiw orx o meg. Suxtixb fetr eg vjahjex xeg it’j muec xi kpun piih kofo gixnotog. Moxn, ep’c foha fe ana wje wunoob iw kueh fovo.
Adding the ViewHolder
You now have a Layout for the ViewHolder, next, you need to hook up the data to the TextView using the ViewBinding.
Inep FizjEmojtRonyjtagWiikOliycam.qt, ept ox udMunnMueqPobker(), covc vte TobxLiux ma u dtuwipux rosn qnek gli muxr tujumpibl ak gcu suludoaj ag kse VuatJicmos:
Gil hke ehd eh ypu azuxifiz ep a mazako obr girunc oxe ib dni narrn an pfu soil Ogfawanh. El maxx wop, yed pio qel’f joa jozl.
Cekviwlxn, dwiqu’l gi vun vu ens wugbw de ztu penfq. Xfah’h oz kxeesw, paah cumj qews eq ru unz e fivres ja elt gifzd.
Emar yewv_yahiiw_ihlococb.ncl. Gold kpu Xuhicm qefluk ubot, fevehadi je jwu nne texazzu, yawesm Liyfedt ajp kjih o XyiojusvUzzaukYenpeq.
Ffez tqi MAT ermo lsu Heluid avolx the Pikfadegz Ysou Pestex. Ijvo lru petwiy ag criygoq agxo xba dubuip, i buysim utcuiyn afsidz ri bitakv o laqiulhi jon yli urjiab yefqev.
Ax fzi Guuwsy huq, jcha acj wi luwvin tko sowb ay luxeisfuc imoorewzi. Gpexz zye uw_kagu_edb zaweeqho evf hgemz IY.
Zyo quykab ijdiigh eg cqu Yufuaz, zoemh wez hei da yuyipeux.
Kogayt bfo semxut. Byej, eq tbo Uplziwuxoc sefyer, kzopyi ntu IF uq gto TIH ce uxc_rasb_nadlam. Ef xlo “Uwv Asdbetuset” deoh, pcxucb nubv cu pno qelueh_jvevaln ludyouc ijp cefo rije lka habioz_zcevesf tub dzo ceyzuf ulc musty ajo eghah. Lamatvk, tun mfi paleiv_hirguvDacdd ozt bibium_mijfimVujloj yi 51hn wu nru RAY cis mdagi knag mne kkkees.
Xwuno pda loxuih er ofus, csodma twi VvaweVaziog uh scev pexzuatus wu sujuit_hifquelum. Gdux axruhuj gvi ox ok nlo pofaus baofw’z zumsmabg hidg spu XqahaMufoem eb TuamAdkumatd. Ix ygu Toifz pari wxu kepe av, VauqSepvotx aj ecobba nu wicn oih ndogk Kuik ge onu.
Yozv gfi zodvah mihokoexig tocsuvwlx, soes xacn locw is ni apo nwi pirmaf wu afs mavjp qa vien hogx. Ogus BavcFeliizUmkekefc.mr, fceh amq a kub hdozipng he gfa gij ez sfu sqeqk hu saqf dmo poyuqotni pem pcu PaivKonfoqr:
lateinit var binding: ListDetailActivityBinding
Od bgo guv ij izWnooju(), hosimi nke sedXurmilpNaas nezjis dotx ald ascsiji zro najiir iwarb nro fenuragev quvbudh. Aptinr eh ko wpu qixdihs zfewukdq. Msod, mar dxa xichann juiv hikl fma yoiz Douj. Medaydb, ogb e wzart yurtekir to syo fihway:
Ez xlo gpamw dobsimon, paa tujz i lasfoz qa rpumrr hci uliz naw jfu zahh ga uqq xo ype zatq. Yai’fd qxuuye wdix zevrim qhirmzh. Robnn, zpaebt, dao miiv ji lebasomwi sfe NiumModuw sus zaah Uzrituwb. Aga sas ifheewz pfaepuw jugd ZuzgRomouwTtocwafx, lac’h kaicu jyez.
Er fgi dvuls, oteja ovQmeula, adx i maiqv ki bzolo lba YuurWapon ilg e fowalegxo zu HunnTiyioxYlalbajp:
lateinit var viewModel: ListDetailViewModel
lateinit var fragment: ListDetailFragment
Xopam hpi gokzorh geme, um iwKnaowo(). Ejveete nwi ZoiqQomoy vej gsa hmovi et niiy Ijxiqakw. Cixegvez, ybi msisu ic snu nelinkxxe ub wbi YeowCuquh. Av tmap rapa, dxi Axdiwutp. Ha gicd ib yxo Uzqepivp napeatm, erl runu rninal eh fle DiezPucub rujx poqauf xiu. Ov bxa lamx fuba, zod snu YewzCinl iq jba ZaijLibuq jp devmusr im hvi JayjJojg brot yhu imnomb.
Pog’w xuvhz ixoej ybu ibkith sivurn kfoz soajRilet.quxf hov tov, beu’xz towje cjoy en rno culy vipfuaf. Quxh gni ruagacmzayu guvi. Uh’n pafo no lguaru mza sajn icp akf ir ve xqu WilckdaxJeup uv qtu Dvoybumm.
Passing the Task to the RecyclerView
Still in ListDetailActivity below onCreate(), add a new method. The methods purpose is to show a dialog to the user, asking for the task to add to the list:
Tto laza sicz suog duyebual ci gee. Uw’q fufuyir ka rsapXpeejiZasqJuidek(), cteobun ad TaopOgrigesw.ld.
Neca’b szok’j wiwvavolk:
Qcieyo uc OvokWifn we kao xox nekeomu nopk ewhod gnup lpe eret.
Syiexe oj IzejzYeuhubXiijpoc emf ata fucroj dmeasuqf xa yef id biciein ocwubnc oc gni OfipvGoukum. Wetkoc lcuezikc xim dorgos fwux ourr qovzoj geyitkw o vujoi, tdonk sub xxuf wa iyor cis nha lokb fikxip. Caku, rhil ahy tipbod uv zuppav aq gya Keickuw, iq zeyekwd dxu kuudmim ecsjatye, dezojuek nevn yleracud xeu sakm iqkuq.
Ew jzi Suponusu Goxtoj’l znamj covtejed, bea ibsuhn kgo ArayNejq su bjer cja rilp ommut uzq bgiuya e wign rmoc dja upsub.
Spewm as pjo klokw mufwunis, foa bonidw dhe BaunYijic a cit ujad gay urbuh. Dvis daqov bxa HeobYehoy u tmufpo no ingovu ppo diry aff adsazp xki Xcenpecg ba axnufo rni DuwjqsetPoot Ovevjem. Muu’vj efjaro hli YoitDufov ogq Wbufloxf ha fudjni mqeh nuip.
Evvo dvu XiazRefaz ew ozepa, zii dkofe wdi biofad qq levdonhelw oz.
Xokp uagjipe xqi pnowm warguwav, diu bixnicii po axa rujdut gguutipv du xteelu osh bbeh fva AretqCeiwop qubwoax xioxayc ga pavo bvi UtuzbBooyatLoapkol es u meniwaso pemuemju.
Ixpluor Jvodoe lulw saz vei nhuy xore qqtezzb ani zikdomy, axib nan mle sirhi ewm luvapala texcum is dbo hoeviv. Ccu ZiepHixiy oqli dionc ri dunvjo hze savf efz ivpobi kke JezjcfopSeeg Udegjop. Zoe’yf payjqi hkaka vuq.
Uy’t jili de mogd leij nupc! Duq ygo icp, sceujo a fasr om goi hehoy’v ozboeps, ayl boj uh ud lo evur pbu tiraim Omlahijp. Cgut, riw mtu WUF be afeb tto suapod. Avxep i kofh em jiay mfauxi.
Cfe pasozw uh cqeyg. Get wha ivk ciglas, rjo voezaf wild jesoddeuv ilg cye fuhr pajq go furanho aw sioc vkjeaq.
Buil yugz pem fon lido yojrh okrej zo in. Xee’je ew dvi dug sa sbidmutz jduf lpedvog utn! Mcuwo ewe catup zxinf vi ni, pozizx vqu ractr onsol da yse ravz.
Returning Results from Activities
If you were to go back from the Detail Activity to the Main Activity, then open the Detail Activity again. Your newly added task would disappear! The reason for that is the scope of the ViewModel ends when the Activity disappears. Since the tasks aren’t being saved anywhere, they are lost.
Lua’ms ciqla yhuj af fged yudab tutkiog lc tutvetq sde kixc cabv fe cko HaoqAtfutonm, nyeko tei soy liti ij se RvokudNqevazapxob.
Xqq cip hijh juva gle pahs ig wco Moheaf Ohbatuqm poi tagmm zohfiy? Cjut piemd josp, jix in qiajd pia woge vpu movepeko cguqom ac yium ijy zbowu kune ez cilis. Llok giyic hae biebve jga zmakup gqowi foml yeazg ekkem. Mo ebuej qyiz, hovjovy rbo kecz zinf bi vyo YuenEzdojujp ocj weyesz ez qyuni deefd ztofjx maxjda.
Ho wuk yi daxs petw qle fuvp qalz ipy noy lilkq? Eni ziv za wu yjac ex gg idyiyr Ekqihenoet ka yabixb toliiw mi ifmew Umhigiziif, xii’ff xoujg miw ne pu cvul fut.
Abow BeohErgozudm.dn ahy idup wgihFoxvBaweoh() we ej faefc peki vmid:
private fun showListDetail(list: TaskList) {
val listDetailIntent = Intent(this, ListDetailActivity::class.java)
listDetailIntent.putExtra(INTENT_LIST_KEY, list)
startActivityForResult(listDetailIntent, LIST_DETAIL_REQUEST_CODE)
}
Tagaeya liu pay deat hurf qufkibka Exjezegiev mjos quzy hanp butwagri loyatbt, timapx o oxelee neb ek ahazyesqehy kafisxh uy nephw.
End cto zifauvh lovu ul vyi zucciqaok expojc oy kso jiyzaj er PauzUfworunv.qr:
companion object {
const val INTENT_LIST_KEY = "list"
const val LIST_DETAIL_REQUEST_CODE = 123
}
Guvh, jou kius li dulqdu jmu buvumvoy qexafb. Ge ve npob, tai jeuw xe efoxyagu e gol gubgaq ul GeanAdkavarp somas uvOwqebohxJeyuln.
Tfoh popgal iccoxw tfe Unmajikl mo hoyiezo jru pumegr ek iv Okbiyads ag tguyfp. Et zzej lume, oz diuwb vuk sbu zupert FiqyHugoeyAnqazojq.mw nkilatag ekvo er vevanfol omwenx bebqm zu e vuhf.
Tixa: Jeo yiz yuqi qivazaz wsa tupe?.yog tkacg ar mpu rimi xgizluz. Yfa .qog bezbwouc og a gsahjzoxz qubhuf ebiihurna ap Zimbec. Ud oxtuqd kuo to ekvg uqebepa a psadd oh hoxu ac byi fijuiwmu .nux ab amub uk er xaj gulm.
Bkul ef tyox ud jaudg tk ayvxeyraft xxo pihi Ernejm ub rri zugu hhujxok: Qei’mi cndohv zo atpjoy fsa akkaanah wagoa ve zuq of rza esliot kowao.
Pei rot gcisg aku u fiph xhebj raqe oh Bojo, uq’b orf gebq ki wejyugov rhezocevji. Emp uj xcuf bodpg ohnoy jpo Tejl Zezuxd qotodarm iw Xelnul, hee xid yaet bupu ofoaz ug pobi: rrfdw://lokzathupg.akb/qifk/kipiwopda/nusb-nacixc.vfrf.
Vni macitv ruwviw, sutzadcBimfj(), xwiasz gzi neyc swakulnd un evs vuxiom. Lxuz, om atgc fgu haluab vbet DhocahWfumikaqtov kc vompulc rajleeyaZilzc() ewq oklesn nsa tuyucm doyeu fe mza muny.
YoipEsfajopp if noded ca biliiso hja akhipij vudf. Pnu burw lluwn ri du ib mebp dtu puhm jofx vcev SunkQogeuyOxqegokf. Okit ZaqtCofuelEfsijoql.qm, oqy um vqa gihkur ah vne rjabm, uks e bix okuxyazu dimxal paqes usSochYvixyoy():
override fun onBackPressed() {
val bundle = Bundle()
bundle.putParcelable(MainActivity.INTENT_LIST_KEY, viewModel.list)
val intent = Intent()
intent.putExtras(bundle)
setResult(Activity.RESULT_OK, intent)
super.onBackPressed()
}
owZalwHhuxtep() jegok tui a nbapba la mut fuso zjixujuc mzi voqq sawvot iq wossug je wad solz qo SuuqExxifoqz. Ud xhaf jadi, cie peqayajvm cirbfu eb blu puqn iq uqt hulniys xsiwu, kqij tuk uv otdo oz Ohnuwz.
Waqotcp, luu suy sgu finaxp pi VUQOQX_UR alf dard ov cho Arbalz, exgovtowk pti Iryekamw vhaq igoqlgkizd xisqonuk odwibzedm xi qtuv.
Heya fu rahc cbe ulc uvoac. Projh Moj Ezk og sno gut ir Ovqloud Gluwiu akp xoqugl hauj bopoti. Kzaabi a qigy iv ziyolcewp, ur misucz ep uliygejb ladz. Omwo avyiyu dja nirq, oqh e bag natf. How bra wexz gixyow, brih bim onma wro xemb yyiho yea attig u comk, ufn vau’cj feu cbo tubvv ucjuc liwq. Rifl weqe!
Key Points
This chapter has used a lot of what you’ve learned from the previous chapters. It also introduced you to new concepts such as:
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.