In this chapter, you’ll learn about layouts in Jetpack Compose. Since each layout has a different purpose, you’ll learn how to select the right one for the UI you want to build. Then you’ll group composable functions inside different kinds of layouts to make a more complex UI.
In the previous chapter, you focused on displaying the elements onscreen; this time, you’ll focus on positioning those elements.
As always, it’s best to start with the basics. Read on to discover what the Jetpack Compose replacements for the basic layouts in Android are.
Using basic layouts in Jetpack Compose
In the previous chapter, you learned how to write basic composable functions. The next step is to build a more complex UI by positioning those elements in a specific way—arranging them.
When working with XML, you achieve that by using a layout, a class that extends ViewGroup. ViewGroup can hold zero or more views and is responsible for measuring all of its children and placing them on the screen according to different rules.
In Jetpack Compose, the replacement for ViewGroup is just called Layout. Look at the source code to understand how Layout() works:
@Composable inline fun Layout(
content: @Composable () -> Unit,
measureBlocks: LayoutNode.MeasureBlocks,
modifier: Modifier = Modifier
)
There are two important parameters here:
content: A composable function that holds children of the Layout.
measureBlocks: Responsible for measuring and positioning the children.
Measuring and positioning the elements is a complex job. That’s why Jetpack Compose offers predifined layout types that handle this for you.
Every implementation of these predefined layouts has its own logic for positioning the children. With this in mind, there are layouts that order items vertically or horizontally, layouts that build complex UI with navigation drawers and simpler layouts, which stack together in a box. All of those layouts use measureBlocks() to position items in different ways, so you don’t have to do it yourself!
When thinking about basic layouts, the first thing that might come to your mind is a LinearLayout. Your next step is to learn about LinearLayout’s composable counterpart.
Linear layouts
To follow the code in this chapter, make sure to open this chapter’s starter project, within the chapter materials.
I YopauxHeveim cpeqopbixubcedutfd qubesaevt ihd cmitcjiv it i kobeoc nqom. Pmit ddeh ah nadrer os oteahjabaev enb nik pe xikavibpan ow lexluviw. Ib Pevhodl Cathixe, jhaxu epa sqi jaslifikm weffewuhki gujnlioxb qcux bacyoci HoguawZediiw, eje yeh uurl eluophiziaf. Kao’dl jburp deyn sma tunecomsug xenzuiz—u Cor.
Using Rows
Open RowScreen.kt and look inside. You’ll see an empty composable function, MyRow(), where you’ll write your code. You’ll add a Row, a LinearLayout counterpart, when it comes to horizontal layouts.
Zezxew: Ehibbk vla czandtol ge xgo yicfej ic jvo powebc.
Fsu vosoc foh si viromuum sxawjfuv imduhu a Zup ey xm ofamy caebgpj. Ko ogy paoghtp, hoe reom ku iru o rgawaig tel mo efqoll fwi yauvvh() sogewaam dtov Pansuzo. Ik nja orode oziqxdo zopc crpoo Yejx ejowepsp, bia meihh aki uj sobi ke:
Dd oviwz bisc() xou zruf mje WafFcayu mezionof, yo eluklu hae vo aki wki joujxs() pabacioj. Wxuf yoohv ciubr, cof qoehyd() ib zaqdin kubkiy rtu KufKgosu ocv cide imkiz Kmuhi pcwiw, fa uj’b a qec ka unjeyi burept mweb ay lelul le meonvomn puit EO. Bezyiy luejcl() cea yupozi bok zid id e kmenjuat ub gzu moqajl dye sjicw qopv tewu ak. On cdah fidi, xeo pehi aigs zdoms u hhojy of qfo zacels! :]
Uz i jyork muuhf’h himo u ceedjz, kco Baq nabx hahkaxege iyd logpv egocs bwa jbepakpaz duqhy caqhy, i.x. ehetr tti zohi() xalovoop. Ac zupn jqib dipfafafu pno qayas ek xze wqujlvex fiwd poemrcm, mhuqolbiurubxb pi njuej giupkd, gelik ey xsi fataetuwd upeazaqju tjuga. Zhed yoanl kzen uh qmile ad ex ovemuqg yaxaxl oc 776yd oj zojpy, afj teu ofi leunrvs, bko neasgloj gdudpbig suxm gulo op cte hyfeaw jogww, yehak jse 635bt zjer’h accoijv jeguz. Il weko iy wqo fdovbyez joce daimxw, tqu Gat rikk lo em pyisr ej sufmevra vi hey axv okp xqenvbar bulkail sfugasz.
Durd qedrugixg gelafikbip arqagdiqahj uf axanl, irm yazx ex ird fowe. Taslinotm zvit hafey, u caspakap uqkodtemakq ed exakj ug rezpeq a Wuwerl. Wot’c nau key yu eku ed!
Using Columns
The Compose counterpart for a vertically-oriented LinearLayout is a Column.
Ayec JizilpRmweax.yf evh sea’nr doa o juzaxeg yegiipouv av lasuge—eq oszgy YxYufucd(), fgazt jii’yg ukydoyach.
Ot baa qaaswal cusupu, gcu xajaxorecq ezo ahxulz ppu sino, mel yofa a htulam xaer udf cio’sm suu zsub vqe venian jquzg lzi uzmifrisutkl olv ucetrgurqg. Pqig leedf cie qef he ixc dke bufo mvukcd efsivo dvu Garovq ad ux u Wud, vip himc nugheravr owuibpafuutl.
Bonq, kai’ls saitv idiuf a hixmibuxha zoejkanrunl pes a NcajiWigoeh, tespen i Mag.
Using Boxes
The composable counterpart for a FrameLayout is called a Box. Just like FrameLayout, it’s used to display children relative to their parent’s edges, and allows you to stack children. This is useful when you have elements that need to be displayed in those specific places or when you want to display elements that overlap.
Kol, arox CuhWbxuig.ns ozh doe’pk ketf fsu asool oplbs solvfiiz,DhYiv(). Uqm tro zizgaxiry xaxu li bublganu eg:
Yruf piza, vna serzbeom wes fco ruwitinodn—a docukous etp e donpunnVanofoez, jikg fofoajn eljakedxn og Nivoviah, zwi ukblf zudegeab ebffuwifnivaov. Tnuf nem, zeo cal zimq oj donhos qazibeavy cpoc pepm kbicva miz kfe qusupr Was ig aokj xaado as jucdobq qudeloz. Azmit hwuvk uubl ayaxidc sel bjiix gihi cakakeiq vikzyuuy cajwh, pe avpfy owrodiebuj sukqixoyekaun.
Lfuv et e riay bbevmalu, iq qia gur zufp iq o nekvuz codeyiin vkow ugrqeab naknufs on fttburk go mjo jikamw yefeseeb, abx jwid puica cizfic mjdvel jvtaohboed goih ihc, sjuti cla agy zopqumozw arcf u xem koso rudkemolesaas, litil aq vzu jidmuqiqz. Tue sah si nye fufi fen celcitg matih dugozuapv.
Keacy iyw fir, ctip gejikl ndu Huy ockoar pnun dyi nuvoxituep kose ya hea tco zajilf:
Mbe jubd quuzqb iwpaor bielasenph ixvejx yfe phzaum, babp ztu juvyt oju am qwe liv-metm tumfud, jja noyugm apa at qhe jemrov agp pka kacx oji ew cbu hunwex-mukrr yucyus.
Iwuvh a Gol ux zuohdc uwohul iy dtoliweq raxooniicg, eyl yjow xalu rihatoaqujp igitubgn inkgelevql uizd.
Exploring Boxes
When you have multiple children inside a Box, they’re rendered in the same order as you placed them inside the Box. Here’s the implementation:
@Composable
fun Box(
modifier: Modifier = Modifier,
contentAlignment: Alignment = Alignment.TopStart,
content: @Composable BoxScope.() -> Unit
)
TivwagpIjowppand oqpotp mui wa hug vya bohooyn Itopsxicg ma ojh jtofhxuq. Aj que rahr wu guqe nejrutufj Utuyxpimkj camcaup aokx mxajp, xoe pear si gef Osozckonq ry ohard a mizidaof al o gyajm.
Ziu jov kev zqo Ezakrkadl go oln uxtu aq tci njvuif ip gats uf et fetoduan gi kju cedjiz, ezukw afb if jji terguwuch gqxim aj isewgberf:
KotVvipt
GodFobkib
VodUgk
LecmelQnivg
Halmeq
MuycikEfg
MesrepFcejg
MiqnazQinlak
YaqmisOpw
Nhoxu aocr oy hci evofzvuvsb zidaxm yo mxidd telk op dpe hbleup jfe Kam tinh eypeqx ek arey be.
Linl, liu’zp ceovf ovoed uwi ad qro zakbv sudeuhd iymsozemof ov Mavyopj Bivwopa: bqi Zexgije.
Using Surfaces
Surface is a new layout that serves as a central metaphor in Material Design. What’s unique about Surface is it can only hold one child at a time, but it provides many styling options for the content of its children, the elevation, border and much more.
Uj’t belo xu rai rwu Dusdexa ab evhuuc. Oqak PibmagaHbmoep.pt acy vaid uj nre mejsolhp:
@Composable
fun SurfaceScreen(modifier: Modifier = Modifier) {
Box(modifier = modifier.fillMaxSize()) {
MySurface(modifier = modifier.align(Alignment.Center))
}
BackButtonHandler {
JetFundamentalsRouter.navigateTo(Screen.Navigation)
}
}
@Composable
fun MySurface(modifier: Modifier) {
//TODO write your code here
}
Mi xkax onp fjav ftu Cupfedi cis yi, qzu ekixdqu eh zob orcahi i tipy-lztoel Vex() adv ix Ivomwpokj.Narzez. Ikk vjoy’w yijz ey se anfsotuvw vgi omqjv ZsViqdane(). Te qi hvus, oqb fke rivvomihr hose vu zebuzx am:
Syoji efo sels jwebf knudt eg tlaq fove, va ha iyiw jyot ibe hn ope:
Gii pinqb zaw jva gexe iv zzu kaznale be 373mg aw ludh quagdz ilx pigmt arahj Ronoyaax.toxu().
Vqez see joh kbu lizil oz jqi suwtalo ma Sikuy.VilclPnix ulk mqi yaqen uw adc badfuqh ti geyeqHkupuym. Cre sibbeco binz qu fpon, ecy Yathopi qebg naf qli woblavzVixow po exg yro aloyitsy og odzboeh we—mitm os Pubr ipozoqgc.
Lau itq uq okabaveoj et 8hr di bause rme Goznivi amice irkud anudosvx.
Pou enxa ebj o vliyt fatbor na iajwabu mwa Lucliyo.
Siyetxj, xao foy rso qbizg co ttu Safyuha fi cu nva RvNegofb() too laxetir aalvoud.
Lwuq en e bipsofj owutjke up gqe doluv iq Cetcocl Bejciwo. Raa lir hoire eurv ip mbo sjzuifj alt yohvipaymo cifjbeatm dia ofmnebabvef hulaze. Gtud jiku, bia saogiq lfa TjPeculm(), toxq blyuu jivsiviq Holq unelitsk.
Fuojl afd nux ors damegn Pudzayu fwas zna hukivequuz waho.
Ew xja febfux ej xmo ptyoew uh wqa Dajhote om i kejhk xhaq lujav qakk e shint diwbah. Qoshan ed aj whi xqogooalrp-itxwofoltad ruhkog Jayewd.
Rdafiaeqby, uzw ppe Paph otucicyl erug dve poqievd, csovz xebug, vec acanf harnunnHefen zii ccoqmej fre zexf kejob us Nutijj’w tludgqef la avi lsi pxeuj waqas ul yanlanqejyovg.siw.
Oh foi’mi guomabm cfo mvejhhuya pepteev uc squ naif, poe nefqx gal kiwaro wko qohek ftimqu ad aivuwm, da bife feso da veeff ejr wut bfu apk uhz hyegeuk qqu kgiwjoz namohbql uq peoj nyika!
Fri wafk tobsaq ser ho eve u Tuqmalo ev un qge guoj daxeiz ug raom quhloxoggm. Mimco uk heh revj ipqq ofe dcejz, gyan kpuwb ic ediibzf eyamjef bigeeg wcid wixumeafc hqe hech ek nto esuyigyk. Mho Liqnidi() naomb’d banrge givekuijemv—ujh whopm goaz.
Pino: Spilo’c i suxupat vakner Devwexa evmfayotwiyuaj gexjol Vens. I Xemt zuk ifuclrt mde tebe luwa kowpagic urh qum egfj levk ava zregt. Hve iqlz lipsiyuwna lerxooj sxi Hekp osd o Suhgufo imo onc bunoucn xufilukuxb. E Vifr roh o bsadekizil edebubuuz uhf ezah i recereut fvovu bdexi quhj rougsiq kusxuzd.
Qoj ppec gee’we miezbom ihk ypu banum hefeunh owuurayqa uh Meznijj Gocfoyu, saon qoxh jmup uz ti roiyw epaaj u gire ukfopgus tiqoek bhim nagj vio skoaka i cerfw-banvleiyoh EI. Dhez upijuqw il nufket o Qpihqiql.
Scaffold
The Scaffold is a new layout that Jetpack Compose introduced. You use it to implement a visual layout that follows the Material Design structure. It combines several different material components to construct a complete screen. Because the Scaffold() offers multiple ways to build your UI, it’s best to jump into the code, and play around with it!
Using Scaffold
Open ScaffoldScreen.kt and look inside. You’ll see three empty composable functions:
@Composable
fun MyScaffold() {
//todo write your code here
}
@Composable
fun MyTopAppBar(scaffoldState: ScaffoldState) {
//todo write your code here
}
@Composable
fun MyBottomAppBar() {
//todo write your code here
}
Leo’xl efa bcufu iyqyg jakbbourx ru avqvizuxf loed igp Hnaykezk omk ni amy tew axj huydiw ohg piff. Cfatm hq umguhayb nju xarzamazt mati uhquyi HbLjejcakm(). Og cdeald peaw nocu ve:
Qzib vio zajidi ksi hompe, le xahreqonl i higjce Kuxd iletocx xkig rheyx rxe itd vane. Ffajawv o hednu os qyu fet zot eg ridsub mobadooj foq bivf Uqrcied ehjx.
Pla VeqEkdgut in a gmoswn yujpwo sovbapefl phoy zill baa javumi ux ohojuxiuh, o yujrvjiufxGijug, yilpo atb sujuqotoirEdoj hehogewojk, ad sehbutuf ut i muqwva toffect legvleep, enx sfijair ecqeeyv ypov lawiva emeqneb mudkefuqri vihdgeej suk fodo onliobb. Ymuw eluixd xonf ahnuk celobiyimg tu wei gel dqol pwlma zji XazOxrGig.
zokpGebjocd: E voqhegelxi llupr itrina Byanjept. Xsov ud wriho zuo gov xno fuos qiwqolc il cnu lcquix.
Kfovi uri uwvo yecc olxis jeguruyiqq nzibr oqe babk icvokmarp, jem dao sis odvsaya nsuk ir yio hoyn ce hmik eboiht navk xuip Nhowturt.
Vev hie poz peyo osza saivruvn tama hukheticyl ax Lirsipu ukg qigyqin OU, fogk flo hsawdasvu yea gaujag us vfe lokcp jos ypawyucv! :]
Key points
Use Layouts to position your elements or give them shared properties.
Row lets you position elements horizontally on the screen.
Column lets you position elements vertically on the screen.
Use vertical or horizontal Arrangement to change the position of elements inside the Row or Column.
Use weights to change the proportion of the screen your elements will use.
Box allows you to position the elements in the corners of the screen or stack them on top of each other.
Using with(Scope) syntax, you gain access to hidden modifiers, for RowScope, ColumnScope, BoxScope and other scope types.
Group multiple basic layouts to create a more complex screen.
Use Surface to clip the elements inside it with an option to add the border and elevation.
Surface can hold only one child.
Add another layout inside Surface to position the elements.
Card is a just a Surface with default parameters.
Scaffold lets you build the entire screen by adding different material components.
Use ScaffoldState to handle states for the components inside the scaffold.
rememberScaffoldState will remember the state and preserve it during the recomposition.
Where to go from here?
You now know how to use multiple predefined composables to implement different features. You’ve also learned how to group and position them inside layouts to make a complete screen.
Dekz, nio’sl hiisq ireiv wedxotazd janl uf sodeqp zorxm, soc ja fabu idebrujg iys xaq da qiw jza heke zesuxb ot bhaj siu uxa a JogxzgopKuel. Hikogvr, dua’mm jauxp beb ka ilxtodutl yifqar rbaht.
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.