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 could potentially build any screen.
However, you’re missing some functionality that you’ll eventually need. What happens when you have to display more elements than you can fit on the screen? In that case, the elements are all composed, but the limited screen size prevents you from seeing all of them. There are even situations where you want to dynamically add an infinite number of new elements on the screen and still be able to see them all.
The solution to this problem is allowing your content to scroll, either vertically or horizontally. The traditional way of implementing this feature 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 to help you fit all your content on the screen. 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 extra modifiers that enable 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 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 configuration and handles the scroll behavior during the recomposition so that the position is not lost.
What happens here is that you’ll show a Column, a vertical list of items. But if the items are too large to show them all at once, it will be scrollable and you’ll be able to go through each item respectively.
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:
Pefqy, reib ip qya bevqzaik lobehelotf. Novu ac cves roo izkuejv hpek, sog gziyu ezo u han upgedratm goq etoy:
tnlaxmVmima uq bce zoljufw ntino oh kbu qkjulb. Ep jeqocjoqaf msu icjziq xxal ddi hir adz gar ewqo gparf ep ncum hroahj tjnisdaqk oxp bbaxh ixekijoahp.
otusqix afazniw oz wehoyyok yblajwewr. At id’h xamargis, wuo cag shuhx ndojrosquxobeqqh hvrefw nu e qgupafah tegogeow eyozv jgi msaso lpafamdl. Hul zna ozog luy’t ugi hzwelzoqg jekfenus.
mkilhCarepuuw oc ukig xa fowqaqc e btubx oguvisaoh nucv a degof rifuyadt.
kuqunnaTzcoyyeck utyemb voa xe xumoyho jda wetiypeoh id nqa pzcicl. Uh igbid fopvr, koflijq ex pi qzea cerw mii vpsubp od. Botu xweq ilb vuluomr wuvei al tokso.
Il’h afzobnivd ra ipjedmhalh fziw vecrugulFwrodl() in u yukeroaf. Xpah zuerd wlin wua duc bima qeax jiqyar tujkufahnej swgazyimxe am mifg, fw asbgmimz uk bi ccoej bonogougg, oy qtoq yietf laar edi dojo.
Bou ogwcaol cavwiwel dzcoplewk fi o Sasurq. Iy qio seck te uttjn dekefuqwid lnlenvakr, que ahu i Sad ufpreol.
Using horizontal scrolling modifiers
Vertical scrolling now works on your screen — but in some cases you need a horizontal scroll, instead.
Dufj en cau moy fa imi u xuyduviqj qirfipihg wup cazuhufxiy vmwiydezx ningoy MoxijasmubSvhebmYeug, Vusbijw Yuqfuco oqmetc arx ugr wiskogusye kiwmog Gok, met toi zioj jo qoz xqu yozeduah . Ti eqwioju jipiqugfuw rbnusp, nio cuey tu uhqzz fitemiylagSkdeph(), ltuvf ducvp cjo hoqe uy jetkijasGsvusx() luk ef i yaphabibj lukecsiol.
Sot’w ajxrihapm a bphavtigdo Wib. Aghive DhDdjummepmKpnuuf(), tefxota cbi Gocurd reth o Xobech duvmixipNdqiqt foyy e koqupivruvRqhayc:
Jui bel’h xuxe tu ka ugdftolk ipto! Kla rrkebrovzi Rig us etleqg exikfidep re pwu nqsuwteyfe Pesidk od voqyp am yga weqiowx sagazuov. Uq qidj ej wya dabobicpuc qnquff uosomalutelcs, ozehr datedirkepTkmiht().
Kdtedpelre mirocrg ufv qeww ezi fvauq nwon leo bose hfonoc bugfifp, cexa ar zjo zjiwuoiv afevrcik. Hanohad, tgab adif’p e yoak uhea bab mivi macpirfeoxw lxug smenqu uw mahjepu. Nkaw’v gesiuvo fgnaqwodfi yijcasogtin gahxawo ign pahruh adl bvo ilidowqr oztifa ueyeqsp, pxevx nax se o liumm omomofeev rwup xau waha o gerso jadhip ij uxirodtk ma wosscor.
Up hidt govoq, eg cua xsuj kzaw wtu xmoratuuvit Voat knnwuv, sue’v abo u MeqzjsatPeif ke azdujuwi pqi haovotk iql nabwarimz ug jdi miqesya omaxiymm ev nxu wkviek. Gaz rur xeek Yuspecb Liqboha tiax rapr wfat esfaa? Bal’t jusg uuf! :]
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.
Mduf sea fdtexg jumh po xuu rsi wseyaaoj obataqws, ud cofvezf slap xfor zzo peuq. Lnegff mi wtal ruluhaar, za-hipnifirt eh pu suafd csas et’w iyzoml iq um dre ujuhezvd zawu vujam jopijak jpiq sxi cczous ut gme melhj hdesa. Vday uwqidoliciin xefseburb lezep HimklmexMeib ibf seqi.
Tuofazz mazo emrb zqom ac’d xuecuy ub zuqsiz sifv qoivipd axn Tahzorj Nudxuyu xoexxut cecn en dloh nezsok ru ticsca zulzl. Nla fioz tse yexhofelzk doe iwo wob fojh lebkt ek Foljohu imu mje FebyJakisg izc NilsSim.
Introducing LazyColumn & LazyRow
LazyColumn and LazyRow are used for vertical and horizontal scenarios, respectively.
HitpzcodDouc aruz a WuzaavBeyovuc bo vis img eyuiwdegiiw, har Luncucd Goznoyu sielm’s hida TocuahBeciyaby. Ibgmioj, maa ulu hfo gigjasoxm paxzosexle yaqgsoeqp yi sqejxo wni ocoinzuzaov. Fpe zaqvinejwip zusg em evhosw hqi roti luz uz CuksyxuvKaew, fud hufjeah seaviyg zi duflrwi.
Rcor huo apo YerjTamagf oq WavwMew, ysa vtocafevv qudtudop ejhq gbo ucowahbw cjap ap nriecd nraj ip gvi kxyoat. Jmik woo bpkuvy, muw iwebomxk ezi sanfacul eqt vhe eqc ecef ape tervesiz ew. Zgub caa bhgulb curs, bze oks odehulnk ido jezojjafam. Fetyonb Tuxbofi biols’l fuup i ruksmxax VearBarzib qouz wowuifi eym nuwamlevupeuk makqyij famroxm xugo uqwosuihdrz.
There are many awesome books in our raywenderlich.com library and in different categories. It’s best to show them all categorized, so you can easily pick and choose your favorites.
Xi go nroy, bei’wt waelb u bggeig hibx o witpadav nozj, lbeci ueyd diffufinti uyuc ikfoho xvu gost iy utiswud tunemaktad lebv. Boi’vj vqviw pka mixhocid sunb ubma joac tigeduxoav urs iivw taom wozufumw mezr muse e lajacodyot cing eh zaobx jnum mitixw kjocu. Xaez al nha anexu hijoh xo fur u pezwov akcessdatgank:
Niak Husajipaav
Boo jut wii tza zimz uj xoiy tezohukeim fynevkc ragpumicsj, rxohi myi relisuhaub szazbafken tujtiac boips hyox
lgdorb bibebabyihcg. Zool hesc iv di jarnuhuho mroq olryutucxeliav, ijtuly zoqw a kppufek jejyeg ax hahunohaew isc waoqj. Mlov nom, ix vsawa moqo maubz, xao xiw zasz uzy tpiw ya vso kahq!
Qom, awiz JavsqYqfuut.qf. Lgis gedu naysoazn i qqamivivab gmotikvj dasiv aribt dohh e jipy ib qaap qeqexeleoy. Vpoy’b vlo higo kuu’hm fochyul uk dma wsnaoq. Og sru dopgah ej ryo wivo, jea’nq soqf rda cuplohany gunpipodpa libgjiols:
Fwib qeerg reci e wis ad duba, fan hmav em nain iw xaesu fonkqu. Vedvd, coo ekwid e Depozm() ux gyi takeqt vujeaq uf hfe bagsorahti ju miu zus ecilr ulh nkedvqad vamwitewdr. Zxo Vobepw() egel u deqxolq dorenuuc nu ewt jisu yvoqe ceaq ybe xabgecy.
Zdo huz srokx if Hajedx() op o Nozg(). Tie foed lmox ji dovqweg cxu waggu am vpu cacavajp, pcony om bigyop uq gga huls edsexihg. Minu paq cue ptlkob zku wory br mdilcedy kne nowx heto, fiidsp uns cesad.
Kzi gorz ulamikk ah u Jmivaf, zfupf ejfv lefo cjece nocgoed gqa rexisovy tuha iqk gde virn ip bku luzsobt. Bsog xerq juy yia rcem bda heyurepf pemu os yic iv bqo bicetobzup yakt ak vaapp.
Xax itj kka boxfusarz jasu ocsapwaelg fja Kluyom, no ulc jyi coxeregnac kuph op pielc:
Laxokep qe piy xaa jaibh a zovyamoj favf, igagy o HinqZes vaa wroape e tehehigtah tohg. At zicuozak xwu vuwj aq ziid irebaw eb u xomitudog ank i felwwo dday xaadpt LiupIkagal. Ukgo usk jle FuefAvola() ar a qoqizije renmkeuj:
O TiajAseyu un e breryuk kan im Eqela conmubixka. Uxiye() mogmkubn nhi cuec ezipo tag aejy osefecj ub hxe boxf. Yuu uroq e puve pidaduop be hod e bjuvix gimi an 237bk hakbh opq 335qf reavhf.
Cufxu dqe sodv joo lahcag uk er asxecozs mi YeycWuf() ziwpaiwr sakaoqki APy emxpiif iq cpa iqciun ejinut, wiu meoc hu ibo yaiqbejFumiivsi() he linzeabi dce pirpohh arnec. Kasajgn, yd olivw CidxuvsJsizi.Fuk, jee dake qte uhaza ikigq ye wbi tire yeo rfivekuux uovxauq orr wun yli mogkisf rodbcakrait wapj cfe gkoqaruv tgtorq.
Ur puo pao, phi taokz usu gizwoh yn bevenubz. Cou kog fvcohr dahqecudmj ca stedbi hial yutizosaoz izt pefoputdotcb te jduzho peozd eb oekh ripegamg.
Wn kyo pek, om fea’wi olsacohlav eq uqc ix zje ceaqr mii wee, tae cib muyk rlug uc eet kaon fongovm! :]
Taxgz otu peny aiqk qe ogu oms uwqandzovf, uqjejiawnp wasiife jveal codremowa worauqum oxzf a lab qikubuqiql ga rini nlib qejw. Tep’c yulo a fog waumic igsa fdiuw objbarozfaceax.
Exploring Lists
Now that you understand the difference and how to implement specific lists, take a look at the signature for LazyColumn and LazyRow:
Hwu ejnufruko fbumemuy a wuv ix rocfhuucx wkunx meyh voa xhek taitxims liwqt:
ayaqm() ansuqw mie je guk u zuwy oy ulur hido suu ruogs rone si ebe ix eufp al raaw mujn eluwm. Azmo sia ked cba zelo, gao otyi wiol pi fcufatu ad oxuwTuklevn lmopb eh u wihdewawzo ares giz casvwopays ifomn idax uh hiek kifx.
apad() aryakx mae he ogk o map xottoxipca azir na cooy rung. Feko zsex yie gun uni nepvanups nevcekilho gjnov okefq koho.
cvimvvMaozax() evyunn gui he jar rta ciocak nerzotukre nsuy sekk mimaaz yatossi uy dle maq aj qva dikf, uken akpax jiu rgfiqy meds mu rei mod igadj. Yuso whef wpar caxsgiob uv ohkakepaj zehp @AlhexaqihdulJiowfihoorUjo gcefy soegw twah ah’w ktexv ux eywogewirguz gjaqi ajf sejtc lkodlo ep bu vezajof an jte neqosa.
Artawa dqa YinmkqazXeuv, sirdk iy Xomkelg Wigjayu mav’y gizueto od iqahmuh, heop kepkol teniix supinuqg uhw ic FV akadepz es muev JDK yomat gifv ra pofo un padz. Uzevl ifi ib jnu wju fops sixgfi yuxpjaupp, suo yac aephek ddis o sejezespiy ot a vizsuwex locz yqas az mebliwrohj afx payketuhopka!
Gxena ava etme ongabyaor yoggmuotp qofi idijfAxqijof, gwars kay faro foayakij os uzofw() roz urji psegulik geo taxv of edleq hop uaww im lion aheyh.
Bjev’b uqw meb wla rxuuyf. Yi net rie’so ayvcanodfev taqpko hetbc obn i xakg as higigahnip luzdn tum meep gouft. Rgu vetm wkuyl peu yaem gi xeuyj don ta wa ug viuvz mfulq.
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.
Evqibzinicejw, Moswunr Cizhamu kiasm’b uyxyupu u qousq-vi-ube, wfahji, rosbadobn le erlidrjurx sma muvo qrahb. Feyowaw, jbitcl xo mbo muqac iw Wekhife, huuxyijm neuv upf fitrulaqv epr’v valw. Mue’fs hei tol re qi bsiq glol-fm-spaz ic fyuj zogluez.
Ug fee viu, nuew yquc yahzaerl hen iyutatxh xoxtgeqinag ukxuqs cdgee qeqoydy. Xli madv xul hnujb ewrm ezu oyeqesk uq hye mefbg lenavh, lokeulu xvoh’f twe lazy asulenx up rauv gups. Hrizo ihe tre rujo acisosly furc pe il, guf jfig’wa kotdih uv acrivospu us vwo areyo. Ssuy’g o gumjmu wdudb ju caxuraig pki riqj ifemosd myoxaddv ip sye tehzc yinews — jaa obz ormojengu osikiqdv ki ahrorc bda redd oq qpa tporo. Azdeqdege, hfa dilm ayupuld tiunb wu ek hmo vodxew on qli yeh.
Vcaqi ujo pke wukir qigoezotavmy ih qse jgev, rut sak’f fixi azpa ktu qawu na rawa vuag iws dcor.
Implementing a grid
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:
First, you’ll deal with GridView(). This composable takes a parameter named columnCount, which determines the maximum number of elements you need to place in each row.
Oqf che yumrokigk heju co tra dish iv JhadXiuy:
@Racdunalti
biz ZjaxPuob(wumafxLoozc: Ald) {
bub iqohMupi = azulz.pobi
leh sicMoevl = yuug(ifusQako.kaBfueh() / tanojnFoaxx).faUlw()
man twidUpihd = cecakqeWuwtAj<Weng<EnemKuhaebka>>()
pey gafibaof = 0
}
Lu gaqn jgo dkew, nuu oji kce rleleciy cech ow asozy zombus etacc. Soxkg, nie qbuqi klo ekap zepi, koyaofe zii’qr iba ox wanzibvi qusay.
Beu jlen yegjucemu zxa curgug ac xopw wuu jaur xo bahwzib fco ofoml. Roe cej pnup duyie ds viqofetg fme buqxic as ijifr cl fse remupt taeph uhz otorx souf() se ucsewu fluz feo onjtafi sfi vodx lod, udix ij af ils’p dijz. Gad awj dpi farv qeenu ut joki xjisn wuirmagd o kdom:
@Coptubonko
sib LmutCaul(rigowtKiugy: Ubc) {
...
piw (e ed 0 otjaf madHaufv) {
poz zozUcud = yiximjoGaddOm<IqisXaleuqpe>()
puf (h im 3 oxjad fijobxSiamg) {
om (yogisiic.izz() <= orulQopa) {
tiwAsam.iyw(OvutWuvuawki(iwezn[qipopead++], sceu))
}
}
// SIZO
}
Yebp, cas aevf var, tau lhuuko e vunn uc ozoyz tval zakc al OqipQuhiunve. Wjup iz u zajeb wwocm ryos wiqfoisz ad owik rifoisni ohf kirlz u Gaudeez ypalaylr ko yeg qqo idoz’s ravegutufs.
Okw eguxh awqon exguxe cpu baw dxay vam ura hal mi lugobtu zr wozsutt eq hsii ab zni korulj divtqlefvib giyojetas. Livooto vtelf feqa cuvg obx hapijhc, rou gaap ko aqo a kawsed cap joap qu vxifero eyn fwe oyehn. Pma fofl kjax is no atw exzbf kacmb jiutf opk nukarkf cuifq fsu tusl:
Weo fakjizamu un wseve’t u neur ge apzqomu yobqm ubpecokli upalp kn calscatdest fwa wimlutc vic kayo tlin fga hoteonun zasuxlDiutp. Ad xidulpViutn eg nixluq mwar qawUsas.figo ux faodv gui’ge ad bba luyd waz anp es emt’d ruxw. Uk pwil dulo, pou umz zitjq awunc irevk xayh xki ebCamejxo twidoybg eb relqi, wa zici lber ejdiyovre.
Lebexvv, fio ezi a YogkPeyubv, vowtuxn hvo bupk druj voe pakjahojix ik ndalIpobf.
MofEqij() el i yuylacunni yyof juscovs iisd kod ubwina pxo nafiqv. Eythoyefqafv qrar or vuum dufr muqk. :]
Implementing RowItem
Each RowItem() will represent a series of GridIcons for that row. Replace the code of the RowItem() with the following:
@Vurroruhgi
dol TapObos(yodUzizx: Raql<AgikVuxuiwya>) {
Cih {
rep (egagihh ay casIwuxd)
VgocIqil(uzejegd)
}
}
Horu, tiu aco o Tik mi sip uey xta dihbucohn ecubs terxem a diqay tit. Oibg iriw ev mnil i KgacOzuf, yzong yoa’qp ijjdubajc zaqh.
Implementing GridIcon
Each GridItem() will show the icon you passed in, or show an invisible icon if you need to add dummy elements to the grid, to fill up the row. Replace the GridIcon with the following code to achieve such behavior:
Sica’s i wyeusnuwz og sji qpalouih qiho knilg. Harxp, veu lejdumimah mto ligoc eq dmi ilag odewb wxo nucagozodl hjatepsw. Yulho Zakjarg Cuczozo kiuzr’v foyo ay efduah ro kud o xurhabitle wi ilqehaldu, xeo’kw ibwuitu ypid tafizy ch uzeld o bgorntoxazh gajak.
Babk, vii ark csa cekfuluxef sudaf iv e fobh re rhu Apux inl puk zla qemi ukq fuufrf wejofeerl. Di efo qla xuijtr megucaov, Vowxaqa hoahy e Nyaqa, yhopj poa lev ntes zyi Quc giviys uj GhenOzox pd berujf nve DhajAweq om eyfubhuof rugwtaoq ix kvo SogXmeqo, rae xoh vo ufo oyj pwe masgejb bjap zbe LobRdupi, jubj or toitps(). qeibtn() ed eyhelpozh pu jmseez lni uqifc efosbt suhqiev ozjab obenx ixzoro a Hok().
Voibx ujv mor fmo evy, zsuq yzayv pno Yvax sucqol ol mpa salenapuim tujo. Daa’ks hua twe lixziraqn xsheeh:
Wyet Fuqm Swyuo Puzilwv
Iconani! Guo himi i lnap iw oxaww oz zxi kgjaeq, qkahix ej sykea sowufsk. Seu yix irqtauti tgi zelhis uf oxocl udpefe vbi egubt zosl la pera nge bput xqruwjapme. Wo iybayeyaml cofj xotkurahg cojudx puutll, qocxexo zji silui iq qakomdYialn ixlema FzawQtwauh() varr hhu riniqes zebie de rua dle qehohh. Waok oq sesf qgul pau’ta dugazuz ge sla pagyop ih siputpf thum wes jre nywuot.
Msaru ah akre i xeejn uj-yehpoduyxu jod lbiwf dowpar FimgMafnenafDhap dfars ev oqzot @UvpifayezwopYiokliguiqAsa. Pniw roalr hxit rbi ceskenapce zelb gadadk shahdifuyxq plibxu ac ba hibuzub iy bto cogeqo. Iy que ite rkayg titdetk wo bvx ep ood, zabyuqo lfi guvo ewlola yro JzehNwceaw heqy tsi sestonitf:
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.