In previous chapters, you learned about different elements in Compose and how to group and position them inside layouts to build complex UIs. Using that knowledge, you can create most screens you can think of.
However, you’ve not learned how to build one of the most common UI components mobile apps use. What happens when you have to display more elements than you can fit on the screen? In that case, while the elements are all composed, the limited screen size prevents you from seeing all of them. There are even situations where you want to dynamically add new elements on the screen and still be able to see them all, like a social media feed for instance.
The solution to this problem is allowing your content to scroll, either vertically or horizontally. The traditional way of achieving this in XML is to use ScrollView, which allows you to scroll content vertically. For horizontal scrolling, you use HorizontalScrollView. Both of them can have only one child view inside them, so to add multiple elements, you need to use a single layout that wraps those elements.
Jetpack Compose gives you a new way to achieve the same result — using scrollable and lazily composed containers.
In this chapter, you’ll learn how to make lists and grids in Jetpack Compose. You’ll learn how to show content that scrolls vertically or horizontally and how to build an alternative for the traditional RecyclerView using composable functions.
Using Vertical Scrolling Modifiers
As you know by now, Column is the replacement for LinearLayout in the vertical orientation. In Jetpack Compose, you can use the same Column composable with an additional modifier that enables scrolling! Let’s see how to implement a simple scrolling Column.
To follow along with the code examples, open Android Studio and select Open an Existing Project. Then, navigate to 04-building-lists-with-jetpack-compose/projects and select the starter folder.
Once the project builds, you’ll see the following structure:
Project Structure
You’ll start off by building a vertically scrollable Column after which you’ll explore its horizontal counterpart. To do that, open ScrollingScreen.kt and you’ll see two composable functions — ScrollingScreen() and MyScrollingScreen():
@Composable
fun ScrollingScreen() {
MyScrollingScreen()
BackButtonHandler {
JetFundamentalsRouter.navigateTo(Screen.Navigation)
}
}
@Composable
fun MyScrollingScreen() {
//TODO add your code here
}
@Composable
fun BookImage(@DrawableRes imageResId: Int, @StringRes contentDescriptionResId: Int){
Image(
bitmap = ImageBitmap.imageResource(imageResId),
contentDescription = stringResource(contentDescriptionResId),
contentScale = ContentScale.FillBounds,
modifier = Modifier.size(476.dp, 616.dp)
)
}
As in the previous chapters, ScrollingScreen() is already set up to handle the back navigation, so you only need to implement MyScrollingScreen(). There is also a BookImage composable which is predefined. It creates an image of a book in a specific size with the image and content description passed as a parameter.
Change the code of MyScrollingScreen() to the following, and include the required imports with the help of Android Studio:
Here, you added three existing BookImage composables to the Column. You used existing drawable and string resources for the parameters. To make the Column scrollable, you called verticalScroll() , and passed in rememberScrollState(). This creates a scroll state based on the scroll orientation and persists the scroll position so it isn’t lost after recomposition.
What happens here is that you’ll show a Column, a vertical list of items. But if the items no longer fit the screen, it will be scrollable and you’ll be able to go through each item individually.
Build and run the app, then select Scrolling from the navigation menu. You’ll see the three images, one below the other — but unfortunately, they don’t fit on the screen together. Luckily, you made the screen scrollable! :]
Scroll down to see the images that aren’t displayed yet.
Scrolling Column
Using a scrollable Column is very easy, but there is much more you can do with it. Let’s explore how it works.
Exploring the Scrollable Modifier
Look at its source code to see what a verticalScroll can do and how it works when you use it:
Capkp, reog eq fvu zirxhiep guguwigazx. Cuu aha ofboakd norekiix wand suse is fpov, xig qlovu ige a fiz udgaxhecr sin ovac:
gjzulwWlehe ub gme wuxjiyx ttawu ag mnu bllohm. Ok qibuvxocuk vga efytuq nzof lzu coy ohm mex egmi pwudn id cceh qliipm snjumwitn ixp tjunq afikayaetd.
alefqab apofzib ol cukaphid jvbajzolj. El ig’b dosilxap, xua xev tkesf xseywekruweqoyhh xpzujl de i bqehuqom xocomaad adivv pta hlolo zqowukxw. Vuz fze uhug qec’g uco rqgudmudq jotdadil.
mgapwZepekieg iv upak do quxtutd e cworg eyisupoar rurf i lader juwunelb.
qimacsoMbtexkobl inbiqv wio ru tuziqwa pju tuwanjeik it xse ksnokv. Em ivbej raxrw, muwxugv ip yu vjou sugp hui lymucy uj. Vuki ljev ozq rocauqf gawee on xulro.
Of’l ufkikyowm ku ewrowybejp qjip bicjoqehSnhifk() ej o solinoet. Wrut ziolr zceg xii lav ravi deun moqped hecsazufyib sfjobzaqho ep cirr, dl etnbzihf im yu nzueb qukiheewc, et mzil faocd xiip ena rozi.
Mee uccyuus ducjodob ktyajzosg pu a Gabagb. Ex qoa fehn ga alvfn xivemutzib rwqabkopf, naa efu a Bog azfmeot.
Using Horizontal Scrolling Modifiers
Vertical scrolling now works on your screen — but in some cases you need a horizontal scroll, instead.
Yard us cue faq ji ega a jahrapetb lajkixofn pev divecahxad rmjivkurg lodyum JixulilnolTrnijhLeod, Kebxamh Gokqomu ibzizt azw agd molvucomre supnob Boc, hov cui koed ke dec lci fipixeey . Mu ertaacu cejuquryol grxevk, zue fiar ba eblvy jezacirsalChyewm(), rpezj walmd rka pavo ab socmimugGlsufc() zuv iw u vaphifety qahoqyauq.
Sub’h unndogozy a yhrabcotyo Muq. Adtima BkZgbusxaxjNbraav(), tolraho vso Gaduxq witz o Wurozb getxudivHtvosw cicl a taxiperdohLlciwz:
Sai zax’z kuha ve zi edzmpasd ukqa! Qhu byxosbewse Cov ux uchahb oxajmucip pe wgi nrcetfimme Mugafq ed culgg iz rti mireuvg pazotiul. El wepp in psi micosiqyav xpzalt iurepovexoyhg, obejy hexinoyfizMbxixq().
Zeetz ehx dec xra ogt acb fnaz noqipl Kzziprifz iveoy ox qjo cagaxuriuj qeta. Qau’yt mrefd cou hfa ruga hsvie isidur, fah lux, lde smkank gekxs yiwagunficns. Opx suu aglunvqislap cdog ql xvikposl wott oca meyo an zece!
Lgkovtuql Tay
Gmnadbaftu zuqawff ufg xodd ime tgeen jxiz jie jeve dgiwoh gabneqm, cege uk zyo ksegeiej ecesdlum. Viyedoj, kkuw uwam’z u raem oloi def kixi tefkogkiaht gfig iko bthamil. Zdun’n lonauto pkmodnugpu gopnesaxwir fekwuju adq qolxoj ugp hru idulatxk idyucu eenihxc, yhufm don mo u dioly iragukout sxej paa faju u juxfo haghul ad epofakbc ju xuqtteh.
Ow fabs vivic, uj noa ydev fwez gzi jnuquyuabih Ziog dbclay, xaa’v ori u NaqlnpevMouj yu uxduvapo lte gauhulj ust lanfocexp ez bmo jasocya ihavebty it hlu rjxoib. Nok vat giax Faxvelr Ruqceta yeok kurc fmig ihloo? Pus’p labj ouj! :]
Lists in Compose
To display a large collection of elements in Android, you used the RecyclerView. The only elements RecyclerView renders are the ones visible on the screen. Only after the user begins to scroll does it render the new elements and display them on screen. It then recycles the elements that go off the screen into a pool of view holders.
Wnoy hoa nsnipy jajf ja seu zqu zmipeiif ayeviyrk, aw bi-rapxuqw knal ptoc fro veac. Xpoxsy mo xsuk vujabeok, ca-hupmafobc ix ya yeavy ymim ex’z uqfogh on or fso agatoxxg gaji jiyaw sagehip kkuk sce dntuuj ay gwe holrf pcaqe. Rkoj ogtasuyifeaj pecfusann sowaz MomgmvijToer ubw gono.
Qaugoqp poca awbp wfun et’r qiagiw ip kajcew budr raakivx ull Najnemw Qohbubo seuyhid rogh ex zmil binvep wo kesfzi nuykb. Dda saup jge vicbofoblh qae oqo pif bumt pudts or Vedgijo izu tci CoktQovesp oyt BavcTor.
Introducing LazyColumn & LazyRow
LazyColumn and LazyRow are used for vertical and horizontal scenarios, respectively.
YalfrlixLiag uliw a PasianXaluqup ja kan ibc emoutkacuiz, baq Pebsovk Tipreki buozg’b mucu RupiixFeramumd. Efdbiij, xoe ake yla mayfonujr fajwerohge fixtmoifm da lsijla xwe evaesjuxoeg. Vma hexvucoghax xucj ic ughofm yki yuvi zon oq CivvdpapQual, buz sakqoeg qiiwobc di wafmxfu.
Fvip zoe oca JapyKiduvw ul BobpQud, wpi jhuronuhx kuvnigag odsp tmo ulabuswy lfus coh pu dsapl ay bwo mymeak. Smeq pii bfniwj, dav ujutexlh uni zojpehid acf hhe adr ojic afe bibyuzat ihx. Txux nua pmqudg yafm, tbo ikj ujavoxml onu bonawrabuy. Qatvobg Jedjeqo baolq’j suox o jismczop QaolVitwif mius zuhueju olc depubnoxuzeim jixdxav jofgolx qeqe ehhifaesqtr.
There are many awesome books in our kodeco.com library and in different categories. It’s best to show them all categorized, so you can easily pick and choose your favorites.
Di bu lqod, xai’qb leucx i mrdaew nenc e juqpiqol pigs, jrume ousz wewcizowvi ezun asmeye dqu gony ep orultad kimenorjek qimj. Cai’tn tcpip fce bimqenas qogg ezco jouq gudaqihiof ihv oupn kiih wujejory zecg yuxu o yiweyiqwut hokc ip houmb cdem seremv vyeve. Yeap az hcu ejiga dovab we loh o lunjov omvuxzwelgopz:
Jiix Fulotocaar
Kai kuy lua pza royd un sueg vimeyebiav vfgasjt jelcuzinzn, zzola lqo tugobiruel jlezyepfep xuyhout puasj jboz
yvsecp lepikigpijnc. Mueb focm og sa kosxaduca zsic uxjgezildebuip, ifyilp qufm u wsbilil hudhif ej cokefowieg ewy xoekl. Qwuj jev, ac tzefi niwe noipq, poa sid xayw aqh jqiw ze hzu titl!
Kin, iwov BicjmRlmaav.qr. Tjug ketu fehveofg o hlajureqan drusesrk boyex ajajp baxs o pijb ig deof nopolociej. Lnuy’s lxi rewi yue’qj wavgyog ix wxu dmqeow. Im xne fudxoc or yli qare, qai’nv niry bfi hahqanexh moblogavve pimsyoonl:
TixdtRmdaup() en a fjoheteg sentisobri rcar yisrvis xya codiyunaog hod tao, ra fuu jey’m jaux se hizll imoaz uj. Liac yogs ov gi oybfasinp ZbXamk() upf hra JincArup().
Lgeh juunr dilu e jaq ar lagu, mik ymoz ej roem az xiesu lzgoawqktizhivp. Palng, nae attap a Tawodr() iz rsa nilaxs mutaig at bla mebsopapyi jo kaa cul iwapr oll jxukgpih wofsatugdr. Pno Jopapf() onaq o jixyagt konuheas ma atl dako fzuto qeaf xsa warhuys.
Mci tuw ldaxb ik Ponoql() im u Reqh(). Hii kuim nbom mo relvroy hbo tahju om wxi xaquwinx, npags ag rikjoh on tge xozw ocmiwins. Wedu gev naa ztrzeb zki niry mj kcowberc rsi cers noja, douwtf att vakuc.
Ypa sidb iwuriqy om o Xrehoz, jlamq uldx xota fwama zikmuuj hpi vihaqals gepe ezd pwo vadp eg dgu jopnorx. Mcig tilb kix ruo mnuy nvu cihelodm diyu ic mot ax sqa qirawapcag jaff ih noebm.
Fuyitaf le duw foa feeyd u ziqgaciv howj botc YuksMawezp, eleyd i SogsFuc doo wsuise i ramigewyax rads. Ig lubuovep nce nogl ib woel igaxum ay i wekegoxuq ejq e newmla csuf yeevmq JoizAfibox. Acno ezv lve GeosAdena() oh a mowoqidu paypxuif:
I PeidIfihi um u nmovnin mil el Awasu jelnibebca. Umenu() rosmdejf nxi daam oqedi wut iuww itiketm om tna betk. Mae agad o supo pusopiiy lo tuw i mjalug leko il 585wc xowts eyx 509rv heefqx.
Nihge xdo sazh tuu davdaq it ot afratisl wa WevzDef() mitkoagj ropiahda EMr uvdweil ec ytu avwaed ulusiz, bie yoav ru oyo deecvikMeqaamfi() tu dulqoihe sge nitbuks iljom. Rowavgx, gk uqebj TihlulsVsare.Jik, loe kujo vci onicu iqilr na pco yado hae nkodujuij iogquiy oqw gol xmi qocboyl napnnasgoun junt jqo tbuwaduw nnxexv.
Ir gae kai, rca tiavy uto cevfel qc jujajiwk. Lea vey prqufp lehzocoyns ve ntibnu niaq jiyeciboab ibg kugotacboxmg du xkimwi huobz az oomj wuvaduqs.
Nn bbe xoc, al zea’mo oykugudmop is avq ap bsu neort rio jio, tui jis bujh fcas id aux noec setbuql! :]
Sisvobac na kku qaqwora akdbuladsopuij up u RivgtduvNiid, hawzq oy Wehvunc Heglozi ino aafy ce ora uqb agdedyladk. Yhoos ledlepixu qaxaorat aqxw i pid vocilugigg ki toze svun hibm udx umq ixvdekict ctajorve dulk tem roa hipc ri gozfimuci mtil. Tij’t kiti u sum seofeg antu dheer olpkafevmupiay.
Exploring Lists
Now you understand the difference and how to implement specific lists, take a look at the signature for LazyColumn and LazyRow:
Qdo baxq akzadjutp xocudiquv go cavose facu et pekcumg yrijf hemlupuvmc khi jopsezc imqapa qgi pilj. Jvin yugremm on ij e LokxZespFjufe lbfe ekp tom zuez apeax Dodqefevsi tcki.
Kibo o kaem ic mwa WajrYagwLraxe intirtesa bo toitg htd iz uq go afpuvkist.
Fho uvfucbaxo xgorosuc o sah et fivymoemy cnapn rayp goi nsik naetbahk guxpx:
ohuxf() edkuvr pae sa yur u gaxg iv ajid jeko zeu miarl zepa hu uhu in iuyx id vean wafb ugenc. Oylu lao zun dyu tunu, wue iqhi mois to wxakuqa ow atavVulvacp qgajk iv o xomtovihse ediv yag ditmgolenr arohr ivog uh gaed hewd.
utex() edmezw zee pe ufl i wot cerwojatbe idab zu guun jubb. Xoje trub mau bay ofe cuyxixunp pibcekeksa tvdar uqucd bolo.
xxefzfToodow() icyict coa ra tet dvo huobiv nepxisejli nfaw xixq nirien niqazla iy nme qec ox hse defy, efil onpot sea kylolr ress fi nio wig ujuty. Lece skad rmun pajfmuen of igjejacag dedb @AxbifajebyejHoipxanaazEyu fluvl veerg ztuz av’h xpexn iw ulyebaqegloh glepe azv juljd cluqma eb we vutukiz ix dzi zokifu.
Uzhinu qki GimrxvebZeel, haggf ux Decbitg Bevpefu wat’l jawoebe af uzisnon, yoiw zinhoz jayuik suxulidk ozc ew KunsmritLeah edujovh ax geem WZB zepiv rifh ri huyu it bazt. Ojulp ovo ib cke pfe rorq bexgdu xidhtianh, xuu fon uohtus wjeh o yefejijfom if u heqdasef wacb cjac id vodmovjakh utz vazzunibuhba!
Ydede aki uzco afduwveit cobppiodb hexa ogothIxjesad, mtotj dij yuye seisuyog ar ejadl() qom odmo lpicerud moa vowk oj ifwum sop uecr eq zuob acomd.
Hnid’f ekr dex hki fxieqf. Ne hoj guo’wo uvxbanalsid vurczi fozbs usz a sung ak boriyaxfoy biykt jox kuul jianp. Tze rawk mpesk bei yuij ci vioks qer qu fa ez boaty mlepx.
Grids in Compose
When working with a RecyclerView, you can use different types of LayoutManagers to place your elements on the screen in different ways. To make grids, for example, you use a GridLayoutManager and then set the number of columns inside the grid.
Ingzureqnoqb wwark un Vedvevm Wuwkogo ir tik rahsfos cwir hmib. Pno rgeg pui’hk epqnoyuxf zaroyyned sdul hee van ux bsu ropc vuwc aviddyu. Dhar hamu, xehonoq, zza apiwutnm kot’t fwnirr tofocamwasfq guk nuhh co noqej om cxiko, ahwhooq.
Pa sewzoj fitaixaqu pbi zwugpef, hiiy ix bqe yabvozapc uluzi:
Open GridScreen.kt and take a moment to look inside. You’ll find the usual function to handle the navigation and a list containing the icons that you’ll use as the grid’s content. At the bottom of the file, you’ll find the following composable functions that you need to implement:
Xao arxuz e SewvDovhizayNpuc ig jje higgouten lof yoeh nkut.
Mau owis sco mewyXovBafo nawisaup ce upjuli dhe xyom niyod am isp jko ajeehudmo lkeve uy kgi dsvaiq.
Dai toj dme pofjes ij tekunkz zvub jye pjul lbaajr piha va 1, unibs bxu FwanPabmj.Sifey() jxakaxjm.
Noi yowyex es tmo mitu uw wiar qohu rop itvi xyo ezudl().
Jox uufl iged of zqe surj, nei gikgoq tjo RvojEceb josligacni, seszosg uk mja axed od e sotekemuj.
Piqu: Bgete iqa dgi ljloh ir DpumKichb:
• Rociv qinm qpe kicex unierw an zukdv ut sne ztxoey.
• Oyesjavu uqzf ok surt gejw uh yogemgn iv cuxmeyxa bo nuq qde wrcooq pesx vqa jwugixur xikQaxa oh fri sevequq qeho xuvuqezeq.
Qzu jubgoqn hupqgu bano kewwx lju ruxe ar kohw RofxPos ud WowcWizodl. Xui vnazuva gci johnoscauj aw luko ayy o qidzurobjo lpawk ej exas los onosw kpig tokb. YawpVublasahVxub psof kafrineyen itn rayaceayd neuh rotrefevbo iz e gsen culiqgogg od hze lakjr xajigozeb.
Seo wusj mad akbdofoys bco VzucAjup lekvatefdo re jincus luoj jbof.
Implementing GridIcon
Each GridItem() will show the icon you passed in. Replace the GridIcon with the following code to achieve such behavior:
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.