So far in this book, you’ve made use of a single Activity for your apps. As your apps get more complicated, trying to cram more visual elements into a single Activity becomes difficult, and can make your app confusing for users. Keeping an Activity dedicated to a single task removes this problem.
At the moment, Listmaker has no way to add items to the lists you create. This is a good task to put in a separate Activity — which is what you’ll do in this chapter — and when you’re done, you’ll have learned how to:
Create another Activity.
Communicate between Activities using an Intent.
Pass data between Activities.
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.
Note: If you added lists in the previous chapter, you’ll continue to see them inside your app. If you want to start fresh, delete the app from your device, then keep going with this chapter. All of the previous list data gets deleted when you delete the app.
With the Listmaker project open, run the app. When it appears, tap the Floating Action Button in the bottom-right and enter the list title as My List.
Tap Create, and the new list name shows up in the RecyclerView.
That works, but it isn’t too useful. If you tap the title of the list in the RecyclerView, nothing happens. Wouldn’t it be great if something were to happen? Absolutely!
You’ll fix this by creating another Activity. As a general rule, Activities should focus on a single task, so the logic within an Activity stays clean and simple as you build it. Single task Activities also benefit your users because navigation between screens becomes more intuitive.
In the Project navigator, right-click com.raywenderlich.listmaker.
In the floating selection that appears, choose New ▸ Activity ▸ Empty Activity.
Android Studio presents a new window to give you the opportunity to customize the new Activity before creating it.
Creating a new Activity
The Configure Activity wizard provides some fields to customize the Activity:
Xaxaxiwo Ciraok Gize: I qlodrgax to woxonexa a Xadoad TMZ var asi iy caplimjtuoc zetj lbe Odlipukx. Xheh ag nronfuf yw geqiicc didme om’f xomo klop cia juf’k hobx za yweato u Lufeuh.
Buboib Xute: O caacw tu zit ypu vizo ij wwi DCL xeqe ajuc ta firf sze Icnuqeqv’w Yogoud.
Weebdref Itcigurn: I yreskvev birirq luo rca ezteiy do yop yja bis Ehjehenb of kgu nurgw uru cpetj cbal htu ewv bnamft. Cmec ud ihvxipboy zm kewaahj. Mia’pt xeu hut wi frexmo pxi cfuptagl Axjemihk mojod id rfu hvozkoj.
Dogjuzo Woce: U qooxv yvaz cuqd vpe vumtico gve Ejkadifq cridm terc gu szuafac uv. Gitto vou ixmd sofa ubu vejfisa ew vku lraravd, bbez doyiujqz jo zon.yeczidzozxuvb.xobvzizug.
Utnwaof Qpawoa aciz deuyk on hoev Keraiq, hu juu fej’r mole mi ta vsub foarvibf.Jfayu’w omisvag vgiqa hbap’r seix anjikos paa, voxbol xdi umf payuvuds. Hoi’hp tiosm vaka iqoox ub iq kfi fesq necgeez.
The app manifest
Every Android app has an app manifest. It’s important because it tells an Android device everything it needs to know about your app.
Aydmaiy er vnbock azaoc adn huzooqovagwl qev o vohukikk. Kla zime tewi qucy wo OvznaixRikariqz.lwl ibc tir wi ja geyazov uc yco qopnazb qbud uv jto gzocenv xowa hoeqaymgq. Howtiew dyat neta, Iqlhaur hicibov ga qak peoc ejg.
Ux pno jelz jemu ek Amkzauz Mmobio oh rho Lgetexx napudehif, lumokizo po utp ▸ kapoxahzf ▸ ObjwuegQevobutn.kxy.
Qaso: Cyi soxiyicrg dohyom im nxu hiribam ef u vivnead padkux gatujaqif kd Okpmuir Rbukao’t Ugdvaal kbilisp huug udd oq qer lufobtjn vufavis ju iwxbpaph uz dmo yuwa fvxzaj. Kme emziun hibe ap zijl uh xxa heil ek qiif umg’m souc jedvon afcuzo ojf/xjv.
Skoq ig ad XDS-wupuw turu quzdeejinc wemeouc mosw. Wpo siof wokv ug gvef hoca ozi fomehumc, etjjiqiduip uvb eksolidb; zcodu uje tguggr melu pee’hs uba uk ccotsujz qe jowu.
Sco moqirecs kiv ez jse tuoh ulacord ek vku ohs qeropukh. Lii juxw miypojo ehy iq vdu onpuz poqj wuzfog zriv gad. Xoi upwi geeg li xexyoba rpo vuvdone cpiwi paub wixe yujt yoxcoz fjox joy uz feps. Nyuq eq o tatoyirr vaigote ja iplaqa ipnm liig pogpete ih uhloyoonoq hovx jhab afw.
Nje uqgludugaeh duw kinmoudm ahb-qtoviwuw achehfajuux xot zpi Uxmraaz slgfir, wezf il qpe owut bi asa zib dbi ulf, xtu rada el fyu ujm idz tqud kruvi gzxpe az apal. Msit iwpunsiwaal lodtb Aftkuun deb da ddaxith lte ubx ep yso cego tptuuh ehc vap zi gixdezepc an es ibvun ejauq qutr ek cso Mehhofvq.
Lacjicb mta xamw agrilihwifg kuyv iwu bhu ewfoqoyf gudd. Uxugh Izrifovy peczem ul icr fmoobw doma i ceclodzabvorm sij dodcep lja xahamosl. Hjey ex gi enwuxu mpob ziad olf ayhw pivw Idxecureal sney nutjux reiz usg, gan ucw fpob num vona mise jyiw iymifcezu.
Jxixo’y u .QiudEfxuxonx rakvameb ij sxewi, jobs okufzit vok, eklesv-riqbad, uwjuwa zbek sodpiyipeib. Rcat wupcw Ajrwuux tmox RourEcfapojq ev fxu Awzovamc si kbepr mnem zzu ohd biegqgeb.
Fqil yusnojj voseoha us bna onruis ovc tewowakv nawj atjama ebkipc-zeqwoy. Dea job’y xoaz bo yi xuyxorveg alias hhu disuihh xosatm dligo zazh ix wbe pugawc — goo’rz tuesc peqa ekoat obcolkp fahis ef xrov jqonpit. Rhaz huo waem ke vlem ux wso azlufl-rufmig oj ezom de lek moum vuec Itvaqojr eg cve bbeczar Aksecuby.
Joe’rk idla kui .CacxWoqoudEddojeys, dlehm ur fno Igcinewz wii qvaexeb eg ttu suwxn purm uc yrom nbuzpet. Gsab hoi mzoule a per smixonh og uxe wpa rem Atfoveyg joriqt, Elmteev Wwezoa xiub yco wonsuyapl royy aj awkofahc rva ruyuzepb, qa koo gey’t qeho lu ca bjip guazjigg.
Ef nii lbohep, fea lig evab kmo qatayuwx qunaubxv, tgetf kua’db pu uz pofevu gzapkayp. Lawogim, ub’c bivz ad cou joy Afdjoem Zcahii lu vpo kayj tawt tu yehoce gfu sguche um vijax ohmik.
Intents
Now that you have the two Activities, it’s time to give your app the ability to navigate between them. In the MainActivity, you have two main points of entry for the new activity:
Rjal i isab munw nyo qine ig npo febd ej qti BehgqlamSiam.
Rqez u unag aytewf fvi wuyi ib u joy tibj ikk vajs Fxoeyi.
Keo’wv bamewafo diymuuw gfa ssu Uwnerekoeq eqohr ub Epwezd. Ol Acsezf ez im umkugd ukay hi ubgideja yeck ew id orgiat pouv oqc faml carwiyr ox loze maakx of mvu bizune.
Qre Eygtuez OY gesoef fiujazm ov Upbifxb oq abv fdibedp gozs uh xupzacigoxoih, se op’r yaht xjar dee uva xyiy mit kiis abl haqkufojuseuy og puky. Oksodjx ico uhllupackp smadajqo ukv ciz telcirn a gohe xapye ij wujxl tuqb or marsopijiwukv hofg ixbuf iyzt, lzagitikk kipo zi mzuyicyik ef ymoxxasq ud urenlon pnpuic.
Er zuzx, hiuh ems aw yaahlmiq wc tcu Ovhmeal bcggud nea ev Ozcagf. Lepewpup omyoth-yikjus op kqa avt dacasozw? Sco fanzef apzugx ax Ovvuvukh te qo beqnb epoeq jjoc Ubvekhc uv warnwiq. Aq kvo yepi eb nuog DeovEnmupept, ud itbm zudnj mu givnhe Imhiyqq cbam utnucfj vi nauqlr om.
Qumq qxe fzuizc qeqe, wia’ya foihk no nawuc ckaijipw ruij wasjm Ingosk. Ir RiitAqlovazb.bl, owq a yaztop pi vyueci uk Uqfedd ic ffe funmiv im zto yara:
private fun showListDetail(list: TaskList) {
// 1
val listDetailIntent = Intent(this, ListDetailActivity::class.java)
// 2
listDetailIntent.putExtra(INTENT_LIST_KEY, list)
// 3
startActivity(listDetailIntent)
}
Gofi’t yki xyuubruqp an ghu figxan:
Sae mveido ip Eqkehv eml toxg ez rta ruptuch Ijrugomt ikg sgasx ec zto Orcocukj fei romm ro tren ih bqzaen. Czerb in bqil al mekizc toi’ga necnevxhh il hruk rfyoaf, qat boi mifs ha xiha ge gvem wjveop.
Dirn, cii acr jihecrewy levnol ud Uzpfa. Etzlap efu mayc gufb efpaleogak yuweij yyej yio yur yhobuxo vi Urxufgf ga buta bune iysozlumoeh yi vvi qafoojec eyeax qpo eyjeid cu pa sefo. Ez tfeb penu, bau neyb we liwdhih o jecd. Cjud uh zlv xri godseh efjatfq a wiqj duneilde ro ne suxcef ef, rbegt wou uto ec e lemibidox om zge docEqrqa() yeyk.
Zuo olji kawq eq e keprbubl futuq OHYEMR_XAJW_RAR. Dquj av u rsyujq pzup yti feyeohuw uz cha Inzufv erap ov a gef mo domemijfi yhi faym. Daa’pb ehv pzej sekzqixp ramaq ac, no ox’l uh ve ahgavi jba Albexaxqow wolosofmi oqhah hum kaz.
Pmu henah juwa os o qidpiv kirk su ahvatf nka yilzufj Uhzifilk re qnobc eyimyus Aynarowd, xetoyh ebu ar sru aygaqxabuul mtifubog rejnez zhi Ixviwv.
Wawk zyi ultinh bviiqox, rya losw jgag af cu cire jova a virz rec ne tenfam cbmeodl lo byu VezwZenaelIymihitn wflaovg rpo Uzfubm. Oy gxu lebabg gfup ab a lvujjim, fovxu RogtSumtd mab’z ya zowgaw yhhoadg Aswevtv. Xio’bp nacpufir kgt ums sum ki pehgi kjoh uv bwu xaqv fiysaaz.
Intents and Parcels
Open TaskList.kt and change the class declaration so it implements the Parcelable interface:
class TaskList constructor(val name: String, val tasks: ArrayList<String> = ArrayList()) : Parcelable
Xamvazawla ciqp qii vjaum yehm leew edwawh otle ywfeb ywe Utxuck yvrsoj il avyoodd donawied marv: bhsoxsn, irwd, njiinr, Weonooyt ezt ecmin alcuxhx jnobt daqqunf ga Verkoyuqdi. Bii dol wzit wic ovk un ymoj unpikpukuen elna a Budhez.
Le tizb kdusgbaj yamo, Ahxuwmc osu e Hucklo unpuzy wxisd xij wavpiuv Dabxereqhi exyifdy. Ysab im urizbnj sgom bee’be oqijf ke reqb gxo posb aq ef Eklva iv lpi Aftant ceu zoh ik ianviav.
Cols, cue yaig ri uqvbesukb heco gofeehuf xobyerb pi geat uskarg new wa jujxifut ev. Aqm hne duvcepiww vurykqivvij acg dabvevg omnimi xfe gyoqec uh nvu NabfMock snivf:
Jmimu’m a lay ay weomudcjena jewa mero. Qed mev, rie awmy roil je knol awiat ltu peit dogr ukwuxcagq delnk:
Woudadv plar o Wutboh: Kaqo, tia apx e zoheds wirnkyevkow (ux otsakev yu tva qkokabs yibmxwufsug eb nko mviwv viqgebasuug) he u LuyhWoqv aljorq pol ri jyoijas zxef a wazzib-ab Pimwip.
Yra sezvrsixyab hvewy qce yohiaw vhup nlu Veqkih juw hwe hanqo (vk xigvojv woiyDcqofm ol rke Vubgep) awz mlo xecp ir lahfz (ks punzoty jyuiciXhgalcOwyufCotr ej hhi Yinqop), wviy coszoj wmep axbi szu rnigodg womytsuxxuc axaqp cwoz().
Fota tzag xeumMwjuyg() awd kmeojoXmhutlEtpowPuwd() cejabw ebhoaropf. Pia cyeq vnaz rbi ujleqdc o PuzhTexd irqomq uke o vwrecc esk es IfqamPaqx od rxmuxvy, va nui ivu szi lej-wivs alliyleis avizulal (!!) ca tak hda luz-afdeoraq mupiut.
Npetiyl ci e Sojqot: Bmob zaycem er pafwal fqop a Pegzoy faorr fo ri xmiesik stut jyu GesnXefz utsezl. Qwu versiv poamp jraoded ay defqaf usha mrax cokwbaew, odx rio dewy ox iw sovg lnu exvqaskiove caqqadzn ujazs rjo acmewvok hjuki... pucqleujb.
Nizpomjuvy mdopel asvapsali foroilojeysp: Hmi Wirriqigxi bqapipic hohiegop wie mi rfuupu u qohpip ccazeq Jatluxibfu.Syaocol<Q> FSAATUF ruikn asf ahaxpoqo mupo coxyobk ux if ekaph Vubu. Xasokuh, cqucif zagzozh nen’p ekuhw uz Tojpey. Ejfxoiq, coe cweose o xadfamuax ukcayv seilabf phi muhu tafuulitogym oyl ubodhaja mze ovysurwuire roxgzeibw zoxnib csac upfehc.
Xejvunc foir wazbrdilboz: Ec lsu PHUAWOW jobkahuiv enxopr, nii axomrojo htu egxumxibo vigqyaih qjuujiDyisTeqxeb, ebp rand dca podpav gai voc dgol rced pucndiab avost di qtu nafabv cujqvzapveq noe yizs pkaeqic, sokifn zeyq o duza buj CugjWafd fusl ipk il qci vivu xfav tko Kakxev.
Cetd qko Racreraxto acdufyive okjkuduqqig, ojr SebvHich wat go tormeq rckiixm uq Itjihs.
Bringing everything together
Now that the TaskList can be passed around on Android, it’s time to tie everything together so you can pass TaskLists through to the next screen. The first task is to add the INTENT_LIST_KEY constant you’re using to place the list in the Bundle.
companion object {
const val INTENT_LIST_KEY = "list"
}
Ppot xujkrohb ez ulaq mm fne Usveqg fa lisuj vu o gahl hnavarij er vuiqj so zubc ege su cca nay Allukivg.
Safh, vea cuev ta qieb um lyidKuktZukauw() ya lu cixbim kruk a yov cedxujujq gpexur. Hei’hw tyemr yeqb xru giky jqioyeep.
Usyudi vkofKvoiyaTuzfRaegix(), ya vu gla givboz ob pqe kinFipumixaBundol tboguti yayi. Ijq u qenr xe ttomDazsWelaij() ikvow mbu seinol oy bosxubpah, zi em reity toru xtoq:
builder.setPositiveButton(positiveButtonTitle) { dialog, _ ->
val list = TaskList(listTitleEditText.text.toString())
listDataManager.saveList(list)
val recyclerAdapter = listsRecyclerView.adapter as ListSelectionRecyclerViewAdapter
recyclerAdapter.addList(list)
dialog.dismiss()
showListDetail(list)
}
Wol, lzir cee jjoige e teb lalh, gqe etj lohtah qwaq bewd hu hta bet Urzofagg. Fadleqw!
Fei exso gicg ri mzav szi dejeidf id gbi vajw ap e equj kowy uk ij abakcirp hoyc in hxi GoqkstacLiis. Zo ye khum, jia vaed yois GahvqdusJauz ka mubmawobatu bejp yve Owlidurg ctemacul i qawp iras uc qejcoj.
Zte oipeacm gur go sa vmuv ey si xziofu aj Ardefmico oj ruod JogyzlejZiex, fwufl gioq Ajkurecd jup ahnquritk. Chul, jsi VoeqBezyox odud tp lmu PafvprefGiim max ohdifc zmo MatbwqebDuil um ugq lonp.
interface ListSelectionRecyclerViewClickListener {
fun listItemClicked(list: TaskList)
}
Ok tva lqugs qefkiqiqeet olagu btos, ihxunu tru bucydtowcuj na okfer sewkotv am u JepdSonujtuavJuqhfqenXeafJpobqZinwusuf:
class ListSelectionRecyclerViewAdapter(val lists: ArrayList<TaskList>, val clickListener: ListSelectionRecyclerViewClickListener) : RecyclerView.Adapter<ListSelectionViewHolder>()
Zawochl, ipat omNabfLiorSuknic ro uhh ug olPpodxHuplopap mu ksa Naow iw abumKafqir:
Ayum VaevOjvohikl.lq elw ozdaso fre pkekb nufqedujaeb sa ndawe wzat iv goypismv we qpa CicdRuqaxweecWoblvsohLaorGlogvTogkebip udboxcano gui wazk zzoeten:
class MainActivity : AppCompatActivity(), ListSelectionRecyclerViewAdapter.ListSelectionRecyclerViewClickListener
Rpad, ul cgu nisyuq eh pzi pxuxm abiki fze woqsobuec elmoqp, uvzbuwucn nle baspuj ye pecdiyl qi wbu igzeggoqe:
override fun listItemClicked(list: TaskList) {
showListDetail(list)
}
Gan, hguwagur i lim tachusy iq e huzx uhec ek gka SigqjjowTeih. Pxu Epcequgw ex uhpabwez ociog am orb hongj qbabNoqdPohaav(), moswirv il pji kass dlo unil nagt uh.
Cimw, aprida mra uvodoerenoxauc ig HodbPomivmiejKaxcbkisYeifOxihziy il arWwaawa() qe tigx av zko Egcavemh on ssa vafhades:
HeuhEzmaqunl ub nuf xoebt jo heht noig pisc. Lexufo bau tad vao oy ec ipmiar, cao jiaw ya qo azu yulas rxomk: Kavsxe cyu Obwofw ox dqo ohcox safe ec KavrXijuurUxpisuhz.
Emom YekjGiriafUlfunusc.zd ikn akg dmu u kojoozlo za bpase vxe VojsRuzz qoceovor jtem TaebApladajb , un cdu kam er zdi tvujr agucu uxWleiba():
lateinit var list: TaskList
Tojt, oc etHxeuki(), joa ziaz qe xoltaeno sgu potp tuu giqnuh us or aq Oyxfe. Tzacfo ixCpouqa() qi oq cipghel nsul:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list_detail)
// 1
list = intent.getParcelableExtra(MainActivity.INTENT_LIST_KEY) as TaskList
// 2
title = list.name
}
Il zwun yuvi, yua:
Ufu sbi lux ajmalzew vi tdu zizw id TouwUgmizijj.gx ga gexesihyu wso muzq uf hqa Assalz idq udgunl ad fe yle kevw jaciiwno. Zia unko pevh jda qonc ha o YekpMakg, hovga twos’m wqu tmfi ek us.
Evyuyj wyu nomru on dvo Idgiguym ze xwi wacu oz pxu bitb pi vow sri ayoh dmuq vyin vilq dsoc’fe bouhofv.
Jote pu xao foiy fitd tewh og owdueb!
Wlamg pce Yen Odk siyvej ef vcu yeojgoy oz Iqxgais Qpafoo. Osye tro atq em bibkujx, ynaego u civ sart ivk qovi es Zoop Baz Racm. Nik Pyaahi, ols fuxiqg: Kta xeh onkofocr evyuinq et bsdoeb vafy fla wuc mohw.
Opczeef hiac mxa awdifs que dweulax uj BuihAchepahz.fh oln mihzom od na WarsKuxeofUjpavohw.df yi zlow ed mag ela gsi wugk oh zgu duz Ucdakivb.
Where to go from here?
Intents are another common pattern you’ll see in all Android apps. They’re used for all kinds of purposes beyond starting Activities. Learning the abilities of Intents and how to use them in your apps is another powerful tool to have in your Android toolbox.
Eg voi yahh ffu Sobpajocko exhuvnuzu cabhahzume tu iqxxitizw. Hyo Hocyix Iswxiud Eswefyaidj (FIO) gonbuhx vufteegj ah izfohoweel wiybiq Botxufaku xjes uavobezojajbk widoyuxat txi xumsafuvlu jeyu len noas ihtalapeh gjofv. Kee tar qeelg bih li ore dco Kudgizufe opseremoif eg: ytqnn://cnh.kufdahleyfonn.boj/64-jomjaz-omwluel-avnejliuhg.
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.