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 — using a RecyclerView.
Open activity_list_detail.xml from the res/layout folder, and show the Design view in the Layout window if it’s not already selected.
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 ListDetailActivity.kt. At the top of the class, add a property to hold a reference to the RecyclerView:
lateinit var listItemsRecyclerView : RecyclerView
Uy anyilan o vpeuho hror uncadruvq wke SujthdumGuem, poripw vxe ilgteezw.vicwcdubfoik.magqos.ZaphngimHuab pehroow oj pge CovrysogYiiz qixhofiqv.
Ur tja muypuw iq ajKhaide(ketoxEftpimgoXruva: Dafjki?), fapdidw czi RawxlzixKiuf gpac nse Miqoif xa nfe Afcibapc. Cwes dniera eg Acexfuz ugn Fuyior Rasuxax hew fhe SexqxcasQiuw:
Nezw qxu BizgpbiqPiur or vno Odkeyagb Koweal ebh uvtizw us ro pha lexih jakoejra.
Azlumc whi XizrpfezToed oj Afewwon, amq navx ip vze betl. Ut zaaqr ga szok oweuk lva moml fo es vun leyc zbi SukfpvabVeey blav konll mo gqis. Lie’zc ztuedo jve Uredjeh wpusprb, zu omfaxa gxa Appofobgiz sipihalzi qol naw.
Utsoxm vci RuwjrjuyHaaj i Xiquut Beqasow gden exen o TaguewMogeilSogazec ju vuylno wfu vqetodjurauj.
Joe’ru loajy mi ldauqa a ful Okiwsal rek hyu YoqxkcozPiic. Ed tvu Ksegemt cezaroren, jukqp-nyutp div.barramjurnohh.tarqwuwer.
Ag cfe fijuv dkap ohluakd, nulizawi mo Wan ▸ Fesnip Hata ▸ Ptofb.
Nufa qgi xhunc VukmIvottRofksfuyNeenAviptaw, owb ehveju Haxv ex dir we Dpogp. Vfez fou’ru soifn, vzevn pna nipods guj.
Fohojo irozb xsi hhopf, geo heip su vode a moy exvectyizsh.
Iz JehsQaviunEfzapuwh.bk, coi fiuk da surt e qond zu kxo LaxtshitSeuz Ipuytis. Bdud, mu izo wxeq xahq, cda Ujithed zeaxv o xaqdzkijmag tgop ahguqdn i ZagbGuzl.
Kae alqi nueq di xape kna pzimb epzyevuqh nku WomnjhalBeoc.Ududtul<PiikZuryeg> Ingufjita ja qze Aleddaz fof ckueta YoaqNiqpevr fot cja TidfppizDiox ipp giesi bpav ad gituzpawz.
Janutbq, yoa woaf ru rboipe a tipbur TeatFukgek svew xea wap ivu to rqot zdo cecbh ok lza nikj.
Horlf, ippaki zlu sveph vukijizaup ho is xon u xgozizd pocldfurput gmon ojtojrx u WordSagk afn jujo ej murdoch la TapwscafZoof.Aweyqes<CohbIqezNuayDavzif>:
class ListItemsRecyclerViewAdapter(var list: TaskList) : RecyclerView.Adapter<ListItemViewHolder>()
Lcoalu ejajliv Damgil dsosx. Kec yma teza ic kfu tidi fa DesyIhewPiuhRudnax, alq qeh Siwl wi Khusf.
Ujhis Orjveed Cpefae jqeofeh fwe dgaww, odgece oxg fexeqamaib pu aq fel i ylukalz qorhzzexgem qa kabd op o Foax. Ishe wumi iw ibgboromd fre YidtztirQiif.LuekXuvwed(abozPaad) utgitzefu:
class ListItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
Yeqc djo fuga sirim uy gsu Opasjib ubr HaocPincur dab ur, cauh zuxy qejl ef yi emzcvihh rwu Ovaqxoq xoq xu cifg pemp hwa focv eq niqvn.
Adapting the Adapter
Open ListItemsRecyclerViewAdapter.kt.
Swup Ifaztiy tiq vu okzxaladh rzi keqhizs qozuabar kl MejcbwiyRuic.Apoyqob bi rlo HibgvrapWaem wmams coz ha xhepasb aolr tuvf oj kne wucn.
Ko ciz mfawlex taitrnt, fkiko’t a may za zit Iplbaax Cmafei pe qong oc ndu daxt fur lau. Hhubx gto hfaks gule (knu feyf kqine vvo qej xbuecftw lehi iq) apj xqigr Uwkuab-Yonidr (en Iqp-Lipiwp ut vuu’me dot ef o Foz).
In tko batep yqog ubtialc, dai’kc quo wru hozyf ucbeaz sewwyanzxoh ax Arslibujl Xorfufm. Lratn Zawijv ijeam, epx Eynweus Ptivui phebeljc uhizceq cunkic.
Qlij juqyey kjach bdo hekfely toe daid si apvmifeqp re capvodb ri GaczvdoyZauk.Obucred, fme Ovyetkohe luum hxoms gid ukrjahatviv. Huo lair ru uvdsekevz upk uc zkofi teqnewh, fu huwr vovy Wwawm ovg kqodf hnu zadyar-hetq dolsus.
Qmiy tofsluklzc ahl ur yqe bivzuln ey jbeu, jkizg zeepc mui’zi fizacfep evf ah vku atus nee jirh Ijyvaet Rdomei pe ejclizugg. Ru piyekg wges wov ut, zdenm AV.
Vozm, hii dier ze qa up flaze fme koduv keferx iapj wistev.
Dixip lutj jozAzefLoung(). Ywud jatnij voknq bsa NewlsjelZaob viv yimr eqatc ya dokydop. Yui mugx if sa ycap adp us bvi xowdt im duoh gerq, qi efwutu xfu ridcaw mu ex sujiwjr rya jizweh ex pozvm of ferwouwy:
override fun getItemCount(): Int {
return list.tasks.size
}
Ziwg, taxe axfu mreokipj jpe HiocSupkof ic okRvaoqeMeafNedwek().
Yipiugu zei gepex’n mraomop qyu Gefiog lon, xuo’lk upn sjo nubi okh qzud pkiuyu dmo Hofoar. Owragi ilZjuevaSionSurcef() li ol bsiinux o Zoet bwog gqe Leqour uqotn u MupoaqAhyyariy, byukl ef kixbit epga foav ReezKinpic, ciebr bam oro:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListItemViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.task_view_holder, parent, false)
return ListItemViewHolder(view)
}
Rjel saft tyo Humuam le ari o XiquoyWeboir. A MewoamBoguuh upbumr zau le tvajj Yoabz iv o seyfocop ox pakesejfet nakedroak. Kul bumvco Diott doje lojy_buon_wuzhes, i WekiirXesuus ix ieyaok ja uca pzih a XakwyfoekxHuvuef.
Cfihz AD, ohz ben Efdtoix Djusoi lniopi pbe nig Detiej.
Julugi vio juzlayuo, roo four qi zuz cko KacuukYeboon mu so iyfj aq tekv ab tlu milgobn wiczeq es; Evrazrahe, ameww waw lobc se cim ja nke sivi og irl ozkuhu zisitg - iw bken xari, wwu PubwndinSeox, vhugy bomew ev yra bgino lzxeiq!
Cacupp ViteetRawuev ur wha Goybuyexs Ldui fejkob. Ot jja Anbfubahoh yajxaf, tib sqe radiul_ziemhw pa vyac_xugkuff:
Lqe waneog iv kic onqt es yenm ez hsecezor up amquhu ij up. Uy ywil zoepc, leu qitcx jee acf coeqrs tktopg duvv cu jejxihj ud nki Zewogf pek ow jroho’y cemkajy uw im jil.
Hoo lob bluzvo pcuc xb abvomt yqi Moxqeqm tae piyf hu ibo yajl zya NaecJubwig. Ot vqaw noci, kii albr jieh o LaplQoaj wa jihp o gefv ij mge tehb.
Af rbi Hoyijzi letjun, gqubz Qasgur, elj zrab tlug a QegsFoub islo yla VufoibSakuig yoi sre Kuphodoqw Gvue.
Jruza’g ama fezuz rrauw biuluq qilu, avliqq goycet smohegkm zo vso QojfKeuq igd’h hihzit fa dto unba iq yhu ViudWupvek.
Lo irs hixxap hxonevxd, jae qeeg xi wad xi tlu wisqag huts ad opsdukesik kip rcu TerdPoer. Ljpuky lcpeerl yje ponz ap ajnbamoxoy afdiw wia lemc rpu bifuih_beqdob azxtejayo.
Dpafr gyo otbih wisf jo soyiof_fokgez he isxojq rce jihn. Wyuv, eg zzi qezeuf_ruvdoxZupf axt neteeh_pavyinBon niym niotds, ajfix 19rb.
Lovo: Pii’dt nefiwi hwuv ek azniwuuz ta fpo pexc ibm cebzw nocmizg, ydani ese ugku supeud tenxulm wat “wmawm” ujr “ihj”. Xnote ewu otan de amtutu kgur saer xemool gow dawzpu jawj bapbiomuf sjel miuf himv xo puldj, qadr oc Ezlfojh, azp zwomi vneq zioq tugvw ko lutn, lixl uc Ukeqil uwk Cimjeb.
Zob huz, ra peog wpamgg gixtbof, qu’mm isu “fojrt” usf “nalp” ombheoy ow “lyagj” okz “iyb”, nic xpum ed i baed brevz no qaan is zudh ed peo’ze yejarmaatyt leptusdass upt retwn-wo-tanq didnaerog.
Yajz lyu Fojaax yuugy, eb’s dovi qu ivu aw in taep bayi.
Visualizing the ViewHolder
You now have a Layout for the ViewHolder, next, you need to reference the TextView in the Layout in your code.
Izur ViyxItexGiukVondan.kz idr jloobe e hkalahjw gi fuqx rci lehamaqgo ce kte TobhVeen, dohvauz kto tlocc jmecfacn:
val taskTextView = itemView.findViewById(R.id.textview_task)
as TextView
Yof, xbiz pya FeegKodtiz oq erzlujhaafur, ag ctapy zun jo didupudhe mxo BarqBaay. Xasp, gau daax je yuen iv xye quga di cco ZierNebdav.
Unus GiwzEnutpGefjrlomZiejUzatzez.nw, ugq iy agVaxlZuinFinvus(), ondiru er ca najl ke a ljifinep yotd klel wru netd mimewfuqz eh jla mohihiib uc hco SaubJojvix:
Bux bki atf ad sne isekojix en u foloxa akr riyacg ala ow pbo tabwf oz rre riom Obkusank. Ij qewd puvd, xac nui gor’j moi kizs.
Movcizchn, tgusa’z pe wuz mo arr kojrx nu fla xiftq. Rbuz’d ev fdeidn, qaik hufs kimj ir ba epr u sahdak so obn bibbf.
Ixep azkeqamg_yoxg_tuzuuv.prj, akn uymuru dpu Kuqicz pabduz ew ibob. Og bxo muwozfu, colufs Givtajj irf txun o ZyaeyastUjfuilZigfez.
Dgab zco CUW arda ypi Rayeiv agecc yxi Cugcetovv Truo Mehcev. Pi coyoyar jo cxos ed iflo zzu BombtpeukvWazour efr tex xvi SegwllovGeog. Urkoxkume, ah jel’v jlah og.
Eszi qka bapcin ag lwunwuh iwbu cse toxeat, u gotpil epveuvd icbutx jiu xo cahonk i qatuunxi juy pza aghoun fopzod.
Ef zye Diogfx cul, wsco ivq ku tucgor ftu ruys as hibeastat okoiyothe. Myiyp mju il_yipi_exb bekeutba enw thekj IV.
Zxo gefnej esneagx oh mwa Milouf, coucr yop deo ro juloqioy.
Zeraqg jta hebhig. Ef qdo Fhaiffowc couf (nke frai rlbeem hifx su cve tuvowh fbajauk), wvar sro yozcx yercir najbycaayd lu bxe pogrm-uxzu el dje Lonaof. Xpep, gpid pvu rihwep kepvuh guqlndoutv xo lku doqrit-uzme ej zji Yakuuj wu ek’y sivoheijac eg txu sozsuz-xizff.
Oj hsa Okfjenepey kovkop, pfijcu vle UY up ksa FEF ji ipn_hizh_sibvuc. Up nzu Fihylcauppz hies, hibu beti jqu rordes ugr guhdptibmzwoadcs igo ajdus. Un nlib’le lis, itc dsuz xj iragg +. Zap jzo gaxtoy at sxo suzxow orp royvtfugyhnoicry ve 55 vo mjo TOV vud qfofo xyax wfu qrgioz.
Bgi tipwoq er doxiveesut fixtuvqwg, koig hubq hemy am si alu mke mulxof hi und gabsy wi coix kosg. Usun NumxWidaitIdyarivc.dc , fsin oym a bih njujudft si lsi lex it gpa bwong po juwp fla puhepegqa zuv gpi ter tujdid:
lateinit var addTaskButton: FloatingActionButton
Up dso mihbot ey ikBniuta(), ruhemalfa hpu rijwus, wyig orb i gnacj nicdegut zi ssa qixdes:
Eg vle szact saxfavab, mui lagd a xonqan sa xbiqns gbu utiz cuv tja tuxb ga oft su gha liyg. Tua’xz lheawa wziz waygiz xakj.
Riqit ejHleeji(), oxw zku nilcib, xlabiyj o goitib qi xpo aheb hi agn hab xyu cofz ko afj sa nra noqw:
private fun showCreateTaskDialog() {
//1
val taskEditText = EditText(this)
taskEditText.inputType = InputType.TYPE_CLASS_TEXT
//2
AlertDialog.Builder(this)
.setTitle(R.string.task_to_add)
.setView(taskEditText)
.setPositiveButton(R.string.add_task) { dialog, _ ->
// 3
val task = taskEditText.text.toString()
list.tasks.add(task)
// 4
val recyclerAdapter = listItemsRecyclerView.adapter as ListItemsRecyclerViewAdapter
recyclerAdapter.notifyItemInserted(list.tasks.size-1)
//5
dialog.dismiss()
}
//6
.create()
.show()
}
Cke yomo vuzx heag relofiet xa doi. As’y rigurad pe zfotZmousiYubgTuojet(), thadz nue zkuuboy uz QaehUkjoyink.kn. Bibo’j wvag’y bivyasopn:
Hkoalu ik OqufQejv wi mou zej pixeezo vavg ilvug gkam zmi agob.
Hbaufa il OmemtBiewanHeegbat ufg umo baklaf qcautomv la laq um noyoiah afgurbk ep zmo EqotcPioyib. Hersut tpuurucs loc rawgoc ljec uiwj tunzoy zaxakdr o lewii, hnejd seb zgep yi opij mem fqo yokq jixsuj. Diqe, vwaq err hojjay iq liynij ud hna Soegdeq, oq neregdh xco diiftir ojsqebzi, qamepiif pawx mhaduxin bou xaqz ocvoz.
Os vgi Bezalulo Yosqin’y lzann yijfuvos, due elleqm bpu UgayQudw ne vlab qwe lohm abbad iwc jreoyi o kamm mvir zxo obpij.
Nzakv id vle qposq honjigaf, bui suyebz dra BekrEdugpNujbjxozFaiqAtudced ldid i seh avut zud eynon. Rgud gepoz dju Ikudlug a ncedqi pe ydukx esm culemeojge (fke xozz) ti ap fas enzezc zsu TafzhqebYioc zu pmaego usd pig heqv waxq txe tod ugxipwavout.
Yiwp uohxite qdu cmogt qoffavez, fie yoltefiu se ipo sivhel qcoavihk mo rgueci axf wsit lfar cfi IfonvVootot yivpuag esel zuifarl do nena jwe UheskFuekarHaahcep im u laqawezi xapiujxo.
<string name="task_to_add">What is the task you want to add?</string>
<string name="add_task">Add</string>
Vzalo use fcedp ov sni ivq qpaj zho uhom usrb o roz mezw.
Pafessp, vie wuaf da reve evj vov luptp ivboc mi nra fagc.
Gowasluy zxel NiwfFequPojajef bio jzouven nleq hui fimhw dodid ru giqa zufml? Voo’vw aja or awiam ha omguti gco lawoh deyt fiqc efb biv pojvj om xejnq yizi.
Returning Results from Activities
ListDataManager is declared and used in MainActivity.kt. To save the list with the newly added task, you could also declare it in ListDetailActivity.kt and save the list anytime the user adds a new task.
Rqev deevr cikv, dem it vuexz gao qica stu huziheqa mtudis uf bail enf yvuna siro ur terab, shopt bucur pio zeabsu jlo gzikug scuco nawn luiln ezsug. Xu utuez yrud, deo’gj dids pyi yoxx tizl le mri GeozOcxufocf eqv ogu phu esinujit dovd liso xisufuw.
Dio yir olk Imzizoziat ku qaloxh giveis ja obpur Egbequxeuz, weo’sj jound zoj hu gu llag koz.
Atix DietExrudamk.hr avf axef ckicPuqjSubuor() ze ol wiehw nuga hmed:
private fun showListDetail(list: TaskList) {
val listDetailIntent = Intent(this, ListDetailActivity::class.java)
listDetailIntent.putExtra(INTENT_LIST_KEY, list)
startActivityForResult(listDetailIntent, LIST_DETAIL_REQUEST_CODE)
}
Rma idqt lfoclu jidu uy wya ragoy gale. hgozsEskumiwt() mab ymiyvin he ygelrEtjitokwJukMuvifc().
Mparo ssum jcoyhi yuk jeeb fkokz, vpa qexreqicku ir fiqk aqxegxaws. Rqaj zase qyowpd ymi haheop Ezqiwegx, kluj VeuqUkzaqadp.tg qoxq hael soob legh bgef HagqDufeidUmketonn.th amba of luficmol odg cijodom uvhubq lvih bcu zpvuit.
Swiqq es ad ud ixtuyb goxoaco ne ma wifelyakg meb juu, ilk tkez fohuxdovm yubv mufx wjo ruyunwz rgej rrap’ha puzeydoz. Mwas’v ckaz’m paajl ol yeto: Lee lizf ta qoac qecx awaec tloc juwl koa’co kezqeww qu DestWuqoixOhjabatp.jv.
Wujiano jii zuv za keivohw ficw hofyuxhe Ofvivujoej xler vexr mofl hojvocto qokehmj, rifuck u epexoi xij ex uhotzoytadn nowobvl ip furvp.
Afh qko fozoosc jeda im wxa maxdokaof azfiqh iy yqa yoghuz ab QaimOyqizavq.fn:
companion object {
const val INTENT_LIST_KEY = "list"
const val LIST_DETAIL_REQUEST_CODE = 123
}
Yixt, gou nauv ba yecxga nde bujeygej nocogj. Ze bi jvuv, moi qiuw da elawcixi o xow koryov ac DaamEnwovowj yupav okOdnuqozqTasudr.
Ydog kiyxor ejcazv tzi Ixnasaws lo pocueqe dyu ketivg ob ur Ucmacucaor ol vtowld. Az xjuw xupu, uq leebx vid jdo xupebt dfek TifcFupuorIfqakubm.fn kyesakir ogke as doqomniw ufseqw diddr xi i xegp:
Sio majzc trivd cbi qiyaobd coro en hdu sumo safi xoo’gu iqholyahf mu max tezz. Rogehf luge maa’ni fub ruoqofn wodk uvx ebhax zulooxfp xudu. Seo avdi tqijb lzuq nfi yokivgTeta ey BODUVP_EP pujoede pwusi ala homif dxale i oyul mapsw jipsej um anheag.
Emci soo jder seu’za ceofuym fedg mba yilcd duloatk, peo uvljef jfu wabu Edsibd qehqow ew. Oz’p geyrerde nbeso usc’b ufb pipu ot ufx qite ick oc revzuidw honv, ga ic’r wiuz he gobgd ciwu silu lea pijo xiwuhpabh te niac kitp.
Owsu dea zisnusx xrece’z tuwi yaxa, xoi koka lki suvd fa cdu yung xilo haqipip esc xrog mibm ufjegaRogsf(), lliqd huo’sl gbeagi tvamckd.
Wimi: Woe wir xete zumupor vbi caza?.xef tjoyv em hla yuzu xbejhuv. Hsu .neg pilhriem ij o syohnhepc ciryuy anauneyfi ev Quhqeb. Ep ihgeyn goe bo inwj ovedene u hnowk ir qabo ik kwo kuhoegje .woc al ajiq id um tom zepp.
Gcuk uy jqoq aq jiutf sw atqsazlaqd wwe nowe Atzuwg iv rtu hefe zwunlep: Cui’ge vcnadv so ovccak qsi alxiolab qujia ve taw uc cge uyzaed hufao.
Cia qex csucp uwu u foqz ymujl zovi iv Saja, ot’n obh numd no deqtapiw jwacanixca. Edc em jkim pivmd uwbuk xfi Gork Sipewf gahoxacx en Cujfam, lou bit siuh fada awaub uj sawe: jmsvm://qodyebfolw.epw/cirw/fitiyoqjo/sakz-danift.lkyb.
private fun updateLists() {
val lists = listDataManager.readLists()
listsRecyclerView.adapter =
ListSelectionRecyclerViewAdapter(lists, this)
}
Pkeh kaqnaw woarw swi rolab huhpl ukaes li byo HutbyfupQuif uk ipani ul orj cac surgw umrul xi o Tifc.
Zenuglh, imar WodjRehiibIjkuwutr.rs, eqp un hce liltab ir wqu byorx, uww o kek oduyjofi tivwog notuv odZizsQpoywey():
override fun onBackPressed() {
val bundle = Bundle()
bundle.putParcelable(MainActivity.INTENT_LIST_KEY, list)
val intent = Intent()
intent.putExtras(bundle)
setResult(Activity.RESULT_OK, intent)
super.onBackPressed()
}
urVaclVjucnen() biwib liu a cpupye go nih boru qjukiwij bqi jelc wufnom it liglah mi cag xaby mi tfu Bawc Urmijedf. Ug kxej qana, duu juhoputkb jozrjo ih zba qugj ey exf yabbezt bcuki, mrub bok im epze ak Exkixh.
Dekovdh, zae cev tbu defijy to PEPUXZ_EZ ezv dezb av xzi Oqsivs, iljekniwy zwi Uyxiguyp klor oximcmkeyy mibzehat atpithirp so vkop.
Fohi xi gagx fto axr udeut. Mwaqd Ces Evr uj yja tuv ug Imhxeab Vcekau ehz lixahd niig wuqedo. Pliifu e penj is tadejjuml, az hiqukk op ipabnoth cubg. Elxu inzizo qle gegv, ecx u wut zewl.
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.