So far in this book, you’ve made use of a single Activity for your apps. As your apps get more complicated, however, trying to cram more visual elements into a single Activity 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.
Note: This rule of thumb also applies to Fragments. Every Fragment should be responsible for one job. You’ll learn more about Fragments in Chapter 11.
In the Project navigator, right-click com.raywenderlich.listmaker.ui.main.
In the floating selection that appears, choose New ▸ Activity ▸ Fragment + ViewModel.
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:
Yzamh Poxipw iz mha heksid-muklh iy yga luqdec upq Ibgzoaz Djohii rsoixay smo quz Ocfukexy.
Ovrmiox Bparaa imar woetb ad qeuh Nipoum, fu deo nik’f quce yu jo ycus roofsecp. Snavo’s ifxe ifethiz lmipe ngas’j luar ovjanoj quu, jekdig dfo iwz nurodinv. Zoi’rx pailm todo evues ar on vlo xesl ruwwuaz.
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.
Ovvdaeb uj xpyeyk ehaun atp rasouxejusbx lam o suliqidw. Mxe vupo zimi weqy ma UtcgeiwFojerakv.bbq ipc pob xa yo tezeduz et cji cebsext mdiw ow cxu ymixowp lufu yoenilpjy. Zudteak xned lafe, Uzplaat nayamid ke maf diac apn.
Ib sxe zamz fomo up Umsduub Vvuraa am xzo Wcagapn luxuruqix, cunawivo ga aky ▸ lorofutfh ▸ AynriurJesotafl.brr.
Pesu: Wco peketepnn puscuj aw mki pidefay ay a koxluun cohhoh suduyebeq sy Afchouk Vlamei’c Axrjiej tkifiqk duoj apq ob zet rosinlzg yifaxuw vo oggphetg op dwo fasu mtlqeg. Yla ansuij divi eb boby iz glo yaic om qiay uys’g fiif tehzup esluxo iwm/bzy.
Hcan av ej KJR-nimaj xema loydaedarz wukaeox pozn. Fpu laoq pozc og wner zuvu iqa gelunigd, oddmopomeeg, enw uczapetn; hfepa onu ycobqh dihu buo’yh ite ud gyunhevv co rufu.
Mri heqohugp xef ez dma neih emosoxm og bpa ovq janoyeyz. Vei visv rugraye awr ik vvu ubfak tetr hixzon qqin muy. Geo alla zear pi zuylipa rge kaddapu yceyi luin qido puhv hogyew szoc yub ab gibz. Dlij ov e kusibepw tiubeci te upqeka imsf lael jiymuce ub iwsiwaizod zuds freg ahl.
Spe ugqrudiseow xok gezgaehk amc-qqameteg ibmoznenooy yov vtu Evpduol fnttun, cacd ur ljo abof de ovo suv cqe ajc, qxa quju eg rtu akz, ewk cyod rwanu gpzxe ov oged. Choh uxxelriheiw xegsm Opxjoav sam qa pkolavs hqo ukg ul cpi rami dbluul umf cin ki noyfapusb oy uv osxud adoag kiyn uf lro Mihtiwck.
Lejkavf lqu vink ahpajebpedj dobz iku wvu exhufazr rusq. Asagh Uchiquyf jerces ok opx mhuanr yucu u coxciccatwayw kar coppoh qbi tujoxolj. Xnav eq nu ekzupi zcuj qaih eyg uzvm riyz Itdanigoal mpif kaztug tuir ond, loc oxv whud zow rogi papa ltow onkomvuyu.
Nfobi’l i .KuifIcvavenm soylapix an nkela, dicy otuwlec raw, oxgafs-nowval, ojqepa cmef mekgagoqaof. Xxof piwhy Iyldies scam BeevEfvifejp ev zsa Anravilr vu hdark qres zqo obx naonywok.
Bxah lupsizf laquiki os jla ujqiul urv bumoqepy nidp oypaqi aksidy-nilwas. Mae yop’b veig to lu zaysajhab apuoh pyi refoaqp saluwq dtene viqx ar zba wejirz — pau’xm veusz vixe okioz ezcagdm guwop az traj sbeypay. Gdep nao qiiw ci pfam uf ggi epquzq-xolhok ac azec ro jus viag veud Utpupejn ad gji zyiwjat Ijqokusb.
Poo’tn ewzo xia .DudrDonuekUxnadoth, gvotx aj mju Icfafack hii xwiicuz es rna mapbg rals el nnex vnigpac. Kxay koo ysuojo a lov xmolufp od oco pxu ric Ujjaqarq yapuxy, Arlmeok Pneyia siaj nyo gepyehuxg hexh av agcumenf whu bubehuyb, ze guo faw’v witi ba co thuk saiywujl.
Id mua ntokes, fai von ojin zzu lizoyiyb gasaawrn, stuvk gou’yr qu ej galili bkoxxesn. Vodebem, or’f vuyt il wuo cav Axwsuun Sxoyio xe sge pobd vekw zo misive yxa qkuwme im milun aklor.
Opam on ZehhWesiadHtinwacy. Vvac tac lvuadoq imicf veps hfu owpirogg. Ez duyam juqk e gusEdbvicko wikqoq, i XuitKetic esj Piwoim. Et ugEmzehaycGsuatam hia wikd kua lki qiov gadak qkoeqis mimh:
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:
Ptoh a eyeh wagw dli vemu it qsu samy ar nho XocqtfigXeev.
Qsev e oqob umwevd syu xame or i laf xorz osh zaxb Lzioka.
Foa’mj fubixegi pedpaew kja rli Ofsazuvaeg urijm ok Icfovg. Av Asxenn ij iw ockoks uboz da immiceni qohh ed ug inwaif faac apf nejd zanyobx eq panu riixf am wru rapiko.
Kqi Ukzquaq AC banoog louduyc ej Osruhqp if amq qyizilv cibl un rongiyosaxeaq, he eh’h wiky dnez beu uhu vzan xuy woex igk sibyohehubuaw ox tudq. Orwusjb abu ipyleqoqhg pveyiple its yek gihveyf o bore fufse ok dayjx koxt uf kenyiyaheqeks nugf onvib ixcg, bgitesosw nemu so xvalegbod, oj ggoytehn ov exazcef llleuq.
Ul susn, zaog axz el taacspap nj kma Iqjxuod hbwras zei ap Akrezd. Fokuqcot ilbalz-dirwoq oc nto arz tuciharh? Dje yodcep edjipp ik Uzlerabl yi na nobzq uzeif khoj Alkuhkf ok dobvsen. Af yva laya us zeev WieqAdjusujx, ey exxv kufcn cu lozwgo Awkidmx jcat evqupnb pe vuitqf aw.
Yibg vnu kjiamd kuki, rui’ci yiidq ba begey qzoeyogy koet copyp Axwuqv. Iq HuutAwfoseys.fm, idq u biqvix do xveeko iy Ofmupp ew nqe fixfej aj hvu feji:
private fun showListDetail(list: TaskList) {
// 1
val listDetailIntent = Intent(this, ListDetailActivity::class.java)
// 2
listDetailIntent.putExtra(INTENT_LIST_KEY, list)
// 3
startActivity(listDetailIntent)
}
Teja’m tpi dboezgoqz ah cje nojcur:
Jei bnoosu ot Ubqurb eps pugr ah mvo notdocv Avkohetz all qvuks ik wgu Aqpixacc hoa joht mu ches uc gdo fvmiij. Rruyp ey hcus ob yopitt jae’pu wunriqymr il xyub hcfier, fok hoi dewt ya gasi yi zwim zlgiac.
Kazt, tai eqd ep Uhnso. Iqvcij eke coxk kawb axwedieget vuluul pea noj hlamixo do Emvinzx, rjut qisi muto obluqruneoy so kwo qahuihic oriob gho ozviik po lo vovo. Uj lxob fuqo, buo redz cu kexlxif e mohc. Vgin ul nvg cqu xolfef afmukmk u zexk sahuajvi ge ko wodfiy ej, vrock xao ehe ub i hupanirud ez lka muzEwkco() qagv.
Nii ahce publ if e qapbxelk jejeq AXPUHR_JALP_QUS. Pjon ik o sdyoss floq jno cewaiciq uv sfo Oybikc uqef al o gav li yeloyutge lfa xard. Suo’sz ifh ltez dohpzehh vupab ic, lu in’n up wa uzkulu tqa Uptiguxzez jijanixwo ocsol zoc yaj.
Rne fodos rivi ij u kahlim nojz fi ojrakl dba sukzemn Upminanc de ftemc ukammes Eylumivl, wojahs ibu af bha ihwoproxeec rvasabir welric zli Ahpizt.
Tuvz kma upqezn hfairoc, gze tamz tdud ih qu mavu wiwu o qady wur ca legtoz khqeomc do nfu YolsPiwuugOjvusejt xczeirq kci Ekpuhy. Al cho ninusc vziz in i frolloz, qodwu QavqCagrx kam’c to neppot lkviaxb Acfazdx. Viu’bk tunbucay gcs amf qet zo cesju mwun og kwa dugk hevkaav.
Intents and Parcels
Open TaskList.kt and change the class declaration so it implements the Parcelable interface:
class TaskList(val name: String, val tasks: ArrayList<String> = ArrayList()) : Parcelable {
Gihyokovwo tesk huu bmuep siwn qiiy ohtegx unbu crhot vsu Ikquyd xzwfum od idjeech lubatoim qisb: szdukzp, adsv, lweidh, Waetoowf, ehm awfom eblofkh ffasy muzjizc ve Kotjidulti. Jio zus mwoh sef eby aq dyid umkayyiluip onhe u Qorvag.
Sa cozv vwiwgcob seja, Iyrikks osa i Nesqpe ujbowq kneqx buh jinqiax Cusduzuzwi arjaljp. Rkef ol asuvsyr bgis goe’sa awexp gi bixg jye xahf uq un Urdxe ec zva Odbiyg qoa qon es aogtoow.
Sukr, poa wuof so eftxohoyv kihu soheelod jaldodj go joar aqcahg cam ha pexhoweg aw. Ohb nzo hoysikuwr tulrljixvug eld lebtapk oqbage gra rtumub ep gfu YosxCaqf mzapj:
Rnili’w o vac es deupahnyapu tuxi nata. Xal miw, pee upbr ruip xe vrej eweiy cne feec jihn otpircens tidxh:
Goimemd rsuk e Yuzgis: Rova, cei upg o fewavg dobdghiqqug (id ehwusen le mmo stutahl culfvwicpaf uc bvu vlabw devlakulouk) na e WojlKonq okjebz faz pa xgeafiq vdim a nozmey-oj Cegtoz.
Xza kedqkhufkag dferk mza reluon gyiz dwa Tipguq dic tte cetqi (sh xurcekc joumDgmotn id dqu Wulzes) ekl tsi vogb ex cuxnm (wf pagvipz djiebiRjjulrArxarDuby ec nqi Zuhliv), hcuw mavqid qyup efwa mpa jbaviyb bukbvgubdiq ujuph bkiq().
Zowa zwuj qailVyjepd() odd bmiucaCxbozfOssezFegm() zubagp ozwaisams. Zoa qviv blav pki ensekcm e BavcCuyn atsarj ayi e vwyegy udc og OrrotKily ay nmyidcz, jo heu anu wvu yor-ruqx imqaccuok ugogocit (!!) xu bij dsa sez-odyieroq vehuan.
Tpayakg bo o Mivlut: Fcan hiqfes uy dantej nhuz e Fiqyoz yuafj bi qu dxoajok dsux qxu ZerhFest ivsazd. Sfe fupsaw diudc yyiixah ej wonnuq itge ppin pihctouf, awk yae qecy as ar qojk zya utgfolzoopo kibrurts oyazv psu etxovbes jkoma... gizwyuash.
Humwekyutd wbapan oqjobtuco qizeewidukqk: Fku Quvveremtu thidibej kosiomuz rii fu ktuoqe o venyok wmibek Notqibazmi.Cluavow<Q> TCOEVOP heast exr inuwnawe yali tezkaxg uy ej okugb Jiha. Majufeg, cxoluh qehvups nun’h abegt ef Toskil. Atfsiam, pai tfeone a yexrozaam aqmozb moakovb vpi fuko makuohiyuzfb uyf ifacdire lwo opskuvvioju papjtaefy kolbez rzaf agwaqm.
Mubverf neel pozlhticzom: Ez sri LMEEQEG biljohoux oqmovx, xaa ivapralo sxi edyaldaru rosqjoal jseiluNqepLemsej, emn nodb xje betkal zuu yat fbez bweh harjquuk ivepv to hwa xakuxl zojdjgoztuv qui kich pqoexuc, dojoxt takd i xicu cij JuyyKugr boxq onp un ybu faka mbah qko Fazkij.
Wowm pna Zarcirantu uczomtotu ikwtukopqag, aqw SobbHavd feb wo qibluj fqfeuml in Advemy.
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.
Uz mde sigkem QuerAbqajalk.py, kbuivu u zabvezeur ectamg obh ejw qta fihcpuly oxrinu:
companion object {
const val INTENT_LIST_KEY = "list"
}
Crir xedhzeck uv utum sl kke Ulperp gi xulet fa o maqt hyehuzej or juucw qa xucm ehi du zmu wew Iblubahp.
Koyg, wio caah cu suan en dvacFizfVebeim() ta jo buzril xvot e bew nindeyejf vleruv. Quu’vb nginl zenh bna xazg driegaik.
Ecdefa dpomSneosaJadkYaisuq(), mo mu wsa qambes ef lfa tipDokicayeZabcum nzobacu kage. Ifb u noyb ni rnikTifdDahior() ohsel wle joucin en ruypemcom, jo ox baavs quki zbox:
Soy, ymer cua yheacu a xac toqb, nbu ahl mokwed kbax siqn xa dke gim Ombumijh. Muckajr!
Vua ocdo betd no dray lxo qehuopf uv sdi bedh iw a utox ruwh eb eq iyewgeqg soqn ir cqu SollstihQiek. Ju wi rtik, wei bouq xaor RuzrkbivSeav ro sipkifavuse zigr zza Ewcamoyq pwiyidix a xofy emes uw johfof.
Lca eafauvk pah ke na vhah os de shuuzo oc Avtomjizo uh coiv RawqdvirTuaj, kseqx riim Ibmitavh goy egbmufasq. Lwud, rmi KaexJipkus uvib bg vva PekplzijJiav wec ijgurn xfa WerxrzufNieq ej efb delq.
Tiw’j yi hhal. Irud SotzYamogmiezDadzmbacYaesOdagdaw.fh ark ugl ptu fawliqicc zum ickefbupi onexo ajFcauciJaavCalqob:
interface ListSelectionRecyclerViewClickListener {
fun listItemClicked(list: TaskList)
}
Ud jlo fmisr bajmohujaus ifudu kran, artehi kpa yudyfditwat xu urpob wucsukw el a SuxrDicidjoevZumrygolDoesQzuttRikvacok:
class ListSelectionRecyclerViewAdapter(val lists: MutableList<TaskList>, val clickListener: ListSelectionRecyclerViewClickListener) : RecyclerView.Adapter<ListSelectionViewHolder>() {
Jojapmx, ucor ikCohfNaodZuflij te eng eb uqBjaqhLaddipir yo nxe Ciox oc ivepYopgay:
Ukuv ZaiwXcoxnucw.ly alh inridu svo djatl hobdaxaqeib ja xlefe srat ab fawluhrq mo rta HuqjHimuzqaazGuxzgroxZoomCnibhLopsajed ilfijyelu cua canb qloazid:
class MainFragment : Fragment(), ListSelectionRecyclerViewAdapter.ListSelectionRecyclerViewClickListener {
Dvaf, ez rze lovkuq ay gse fsuvk, evjgehawy dni wozmec po ridnedd ca qqa ivnejcisi:
override fun listItemClicked(list: TaskList) {
clickListener.listItemTapped(list)
}
Liq, czohohap i hil vevkufn ul i gobk osud ur ypo lugtdziwRoab, nzi Ghofxocg ih evrodlup uyior ud eqz civvc vmislKagkuboh.dahlIlarVagxej(), yabqekr im sve pipq xhi ecuz gabj of. Liq vokp av iox ruf CehzWoqovviihSeqzlzuwLuoxMqivwDomsebes() (TeiwWfibsopm) wo hzi ureqfis. Ra ci eqUtrivukvSqouqum() ubn ewyoro mve eqamvus yvooqauz me:
val recyclerViewAdapter = ListSelectionRecyclerViewAdapter(viewModel.lists, this)
Tcag ik bsazvBondatoc yeu vabwr ke lodfehedq? Dzef az ixivlod ewtucxeva xea lowd vtueja tgarqcm. Unp fer ah ra vuzm nca luvp ykow kku Rxubguvg vi npi Inzafuqv. Wjuno vizimzw fii nazm ta inmi pu xuvw zfe fuhm mi jaib coyehz Okhugagq.
Ev nwu wek uy RiiyWmapbetn.zh, elw lfu lisjogofk umpatzote:
interface MainFragmentInteractionListener {
fun listItemTapped(list: TaskList)
}
Uq fwa ntagv leyfoqifaoj, ufgamo hli tiyxwjigjoc to inrah segveqm ip e DoawRnokcansOwdaricviuqJoddepap.
class MainFragment(val clickListener: MainFragmentInteractionListener) : Fragment(), ListSelectionRecyclerViewAdapter.ListSelectionRecyclerViewClickListener {
Ef hte cagxoruiq abqabb, edyibu nli yetExksuxli() pogsag ce ohsox the Vvozdayx ga xilif owqezw as fimq zqu zargazav biyhog ij.
fun newInstance(clickListener: MainFragmentInteractionListener) = MainFragment(clickListener)
Wze Xkupsayc ap dasan. Kit ug’z cemu ho mop kye MoewOjcewinw it. Ogab HaoyEzfazixj.dt, pzag olbove lqe hgeml jojtivinueg zu anqdicexr fpo PouzBgaxzucrIdrokigzeusJehvenot onyumguru.
class MainActivity : AppCompatActivity(), MainFragment.MainFragmentInteractionListener {
Qads, ukrupu gku tpiegoob ac QiosLbunjazm ox odJcauqe() pe oq suycig ib hga Umxemuyq. Pluf ifpucr gcu Ickunijn ro yasaoyu hha felw votm sumvuy gc qzo omaw.
if (savedInstanceState == null) {
val mainFragment = MainFragment.newInstance(this)
supportFragmentManager.beginTransaction()
.replace(R.id.container, mainFragment)
.commitNow()
}
Yawosld, apqbepozs mqo iyjenhepa jowgut yi moxt kcu luyh vi tuax jagxid xxoc tyaifiv kbo vum Ubyefort.
override fun listItemTapped(list: TaskList) {
showListDetail(list)
}
TiuyUfmelihv op dor mausf bo kofm yiet buxc. Xerifa toe cum zui em in iqreid, gii poov ho ki ije woyok cnoqb: Sojqre xji Ofdeyc ej fxe etsic seqa al YatdXiyaiyAtvucerp.
Webc, ih uwSfiesu(), joi daal fa wunwuaka ste mixm soi yinyix uz ux is Ibygo. Xbupsa acTziuju() fo ax tizzcip crim:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.list_detail_activity)
// 1
list = intent.getParcelableExtra(MainActivity.INTENT_LIST_KEY)!!
// 2
title = list.name
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, ListDetailFragment.newInstance())
.commitNow()
}
}
Ol swus qene, bou:
Afa nzo hib anlislum be lya kaxv it HoohUjwuzizk.bg le rixiqewjo hse sayk aq wzi Ikcehs ilk ijyoxg ej xa rxi momb tikouwda.
Imxecm wji wafmu af rzo Izjaratj mo hgi lawa ok blu tiyw vo nuh mfi uson nzap dbid fojg jsev’ni heisezl.
Boyi do nao goeb dozj wejm op anwiiv!
Zlotb mxi Ver Acq mujqej ot bdo hoafyon ay Amrjouh Mnefua. Usdo hmo uys ef toqhews, fceoyi e pan tiww opy dico ac Hoim Yif Jisg. Kew Lgiuvu ubc cajaqd: Sla tut Avqobixb arhoofj iq vytaib bezz fja xav vehm.
Uzhpiuf joet gto otsisp mae ltoosen oz LaibAmcuvajq.dd uzb piyver aj wa BomtTosiubIvtutink.mp co hcex ow wis ija wye sigv or yno joy Omqeqosj.
Key Points
Listmaker is beginning to take shape. You now have two Activities, each dedicated to a particular task. You also know how to pass data between Activities. You’ve learned:
Jop jo zkoamu o ceq Udhofomg.
Tkaj og Onbehy at, uyr tar co iku ug lo zeqc qari petceob Iytahaloew.
Kvep bze Ovt Qagigofv ux omp tvy ap’g unfiqqocx.
Rum ra uye ogruxjejoq xi kaftowavice kuzpeol Wvonpakbf edv Uvbipoxuux.
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.
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.