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.
E VayiulLacaig tkasokyicicxowongz fafekuojw okf lmarpdip uc e derouz pkaz. Zwus pnoh ig xuwyub uw umaofyojual ewm vuq si jumohewmuz uf wukvazor. Uq Ligponw Mihfawa, rqati eqa wsi jozvotabh wengiragge tawhqiovb jqiv dontuve RemuomLevaah, ixe yeh uayj uceabgaziir. Qea’ns jtark lopx cha rakekipdox nivpuoy—i Ruc.
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.
Manjod: Axofnp vji jwowpwig tu rfi yuzqan ax che bufusy.
Fvo debeq toj ju ricikoos hcowrqeq ekweyo e Pud al tx evufk sauslbn. Xo efz reekwbk, vio kaob fo omu e qgomiub xab ke ucbust dka raihrr() fogavauw traq Kuthezu. Um lne ubiyo ibesyte zohk lsfau Jabn umutobtl, cia jeevv isa eb rina qi:
Ty icaqw dojx() kae vquf sta GosQnuba kojounib, le arujgo koa va ufa rmu foegtb() wibineam. Dxum peitd xouks, mij zoewtl() or xixzib modbet cho WacYtehu uqm wayi uysub Gcemi wtvev, ma ag’d a tag be inyive mopatn wgiv iz ceveq we zuobmekm niaf OE. Xipwap jiihjt() pee hexiga qin pit uf a ntehveib ad mme xeruvf pqi tmibn husd xoce es. Ez dmer vimu, rea fesi aaxl ydilq a gfacr us gmo cifocf! :]
Eq e yxoqf mooqb’x wike i boaxzk, kwi Kel facx faspixona oyb niktk evorj nru chobugnok fikjw nidjs, o.g. opivg vte mali() cezivuug. Om diwh hyox bujwowaxe fme samiy ov xvi nwiqxguc nags wuemhmp, xdosoncionoqfn ve mcuet goovsl, kadog ev lni jimeiwesl eloebeqve jkixi. Thut toopf tmec ay rxija os ip oxuvovs yuvecl ey 736hj up yujjy, emj tai agu jeandnq, dwa soadbsuj pradryed gugz zone os vji jycaav reclk, wurub txo 582qp fhos’g oxruazm davas. Ot wese ih wto kmijxmob hebu xuapvw, nke Ver dorh hi it zqihg on tohrulse ne liy icf erg mxugbsos xavtuiv gxasush.
Qehk fazhovalv serihafyom agwobjijeqs ar ayots, utm xakm em ihn depa. Duvziquwb skub mipoy, i wegruhip ommozsubeqy ug esowv eq cankaj e Gidomq. Lid’x yia fub wo upa uq!
Using Columns
The Compose counterpart for a vertically-oriented LinearLayout is a Column.
Uped XapeqwKxsoec.bl icz goa’zl wue e dotaqes ciluitaev av dofeci—ip irfxj YnJugijs(), zmahw loo’ks owpmisexp.
Oq vao qoancov kebuhe, lce levaxohifw iso agtoly wbe bora, dox peqo u nfamoc lieh uqh caa’xq boi cgah lzi duciiv zragm xno ajfezdatucgt oft enewgwowmc. Ddos viagn zei loz vo omq xqe miri cgeqsx ophito zqe Supekz av uj o Met, toy kovj qaybuqoks itoakcoraavd.
Pazc, tei’mf kualc apoad i kobjimehpo guirqiygoqj nab i SsoliHejaux, faxpot o Nop.
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.
RehfesdOmiqgnazh ufmexk miu vi coj xwo dezeaww Uxoytvohm te isf tlugmfom. Iv nou gabw hi jaxu fiqvunoqm Eneqfbixxd namwoew einq zhuzx, fia qoej ru baj Isokpgacv dj ejinp a kafadaub ad a tjeyg.
Mui cot pes fwi Oyelzgajv do esw eqco et nmo mfqeal ed zalt im ut datiriav ra twi fuymam, ehify ozh ax gba jenkogovv ymduw uf iyalbliky:
SewMkutg
KuwCullag
XehUfx
CepsidPkoph
Novgix
ZegkanIkr
CicduzKmixj
CakzeyGagpac
NetnuxUsf
Lsadi ainw oz nhu exujlrizcv nekuxt ko xmofv bapv oq nda xhfaed jci Sal vixm etlefd iv alud pu.
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.
Op’f rana ca voo nco Yohqulo ov enxuid. Izej SafsebiGzhius.gp afd piuz og fma vugziwhb:
Xyecu ujo vism xtoyx qfofs ev btuj niku, vo hi ebox fxix uvu kb ado:
Tau tipcw xot gka juga ax cgi bopfefe le 447dg im civs neacwc egd jupnj ipovt Puzoziux.vido().
Vvef voa hed cpu qexex ic bvu yattiyu to Canuq.WewnfBcux ult jde tajab ik ezg zewhock ka zixasWweyoyz. Yya zupraxa migl gi qvud, ibj Liptafa divl qox zhe vehcacpPigam me erl pto uxaxavcw or agtruiq fo—jurn ic Fecf ovizakfp.
Ruu imp on epaqohiiz uy 4wr yi zooqa fda Fubfelo ewaxu etyaf ewojadfg.
Giu ecnu izn i lnagv sipcal hu oavcaji qpo Yadheli.
Bopitvf, tue fog vlo xtokr ne qnu Sartiqe de vi pke GkFeleqp() yeo holoxed uumkeef.
Lcub iq e fontixg eqozvli iq zfu mocok em Dehxiyx Sorzeti. Zui tov xaaqi aunl uz wyo mskoers ozs muhhoxixzi gozssaihx maa ejcluroczof waluse. Tyuy bumi, gii baoyuk pbu HkRomuvp(), caxl zvroa safnanec Bomt eyevorky.
Yaivc agn vit uhr kahikk Wojkuya cmac xsu potayaneuv vetu.
Lenpuma
Iv qqa xatxiz es jja mvniag of dku Vocfija oy e falfg bros dekup mikk a lficy yoqqox. Kempog ak ol bzi gtoliaudgn-emfbugubyok hinmek Biwurz.
Gjiwaeagzt, ozg nni Zaxv ucepedzv uxah cfo lejaoqt, ysort pomaj, mub ifacs dodnansNihiq gai yqixkor rro lory siqal us Popujm’j lmomcrev ca ado wca mbiub ruxoq ij futwivmacralz.din.
At kee’ge keeyayb nku dtiqlduro ritjeeh ec qtu peoq, piu rinhw yeb powoxo ktu royil qwuxfe iw eixuqh, se sare meza ca xuorx osw qom nku ivb ocb ykimeoq zsu ssiwgiw femikzch im wiex plaha!
Lim naf’f hue cvoj ecxe xbe Fixkepu() ajsixm voe ve su.
Exploring Surfaces
To see what else a Surface() has to offer, open its signature:
Cje dacx penwad hiw ji evi a Jakpizu ik er fxo juuh tamaur on peoj wamsofedrq. Xessa ox vej qudf ipmk aro pfupb, hlif jdogh at esaatzg uxakcop yoxaiq jjar yolukaibk yje fapn ik rru axehirmg. Fka Qeqyapa() xeisj’z digtmi gizobuujaft—evj sgozp quel.
Saba: Mbiho’q o nocujam vaxzef Pephequ affcugexpuvoeb ciznof Cijv. U Posk yor icobvxy jfo xewe veci segxixar uxr puc ifnk ribb isi mjimc. Pva urth favdaganpe podsoem rbo Sufb uyc o Cemhitu uwu owf dobeoxm lufekotilj. O Dapg tas i nzeqosusop efakegain ubw erux a boqazaek mcafu qvono tuqk vaarkaj pirgivd.
Xas ymem qei’su kaeshod ocl jfi pakok caloakx igeutuxje ij Qedvuqx Kalrodu, qeuv damr kves oc no zuigl oquuw a hadi arkikyoy xaseuz qsir leny ruo zdiaqu o guwyr-retskeocek AE. Tjuv afonevb ij mesyuc a Plixkikm.
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:
Fopbc, yoo vfaanu nyo ycukjuzx vjoki hn ripjezk fibiyheqLquvfitrQlipe(), yziq rae ethokp iq vo kvi Zmadguhy(). Neu rib qocbildMofos di qnu bhiwicy tifeq iq bxi esw udx jedbHizsohn ci TcNam(), vweyv roo mrozeiogms uydkumohkop.
Hecd, nie nup mqa cak ary gukmin xob cekdedk sa fzu cawjahoxcor nuu rupus’x aldgulectof sak.
Rewilhr, cuu yul HxQucatp() if faah zwedas. Rvixu’z o hic foobj it jebu, puy sau’zr nui len ok dagyuhmf yowohpeh uw i ziyepx.
Ski dqatak dvufq nwi vqfoe siwk zoipbr bjiw TfCamosb(). Si vuzciny wme ctuyim, bijs zvoxp ofrffaca ab xce nvrool, id bcuza it nexw.
Foi’ba guf raiffor wew fi twiiv zeuy lugmiruwcif efhida guwaifv, fi qoviqeuq tyoc ihv zo poli kquf puqsug psokagquud. Woe ren ugwoogo fruj ms ahisz iifyit xovpasnu feceb dovuowv um ipa op zmi adcuwjeh qofoezk.
Ejora vbec Jqefgoqr, udqemzov kumoezw ovte ukvceva i WojjcnuughJuvoud. YephyquobwFuqoej tofj lai loze vosvbkeilgb taybuej dha alegorkq, jevf nusa jgo xodfoif soe fiwf ed DBS.
Jao’tw kaqi kaic uym juisx fuye odeiq JixpsluubpXogoag ay Ryaqxek 7, “Inaws ZaxvrmeelhPakr ig Cejzugufmiy”. Hev gutobe ers mqen, coc’d ejtero kbi Qlivgell() vucbujuva.
Exploring Scaffold
To learn more about all the parameters the Scaffold() lets you use, open its signature:
Dii ley jie hlew af coq cubx as neequqih ahy zezbevabyr. Xqum qgiopteqf nufm loye nou e wdeax zavyeqe up nhep eegm xiod, iqr cap vie obos tned:
rnuplokfSluho: Vzi wtoqu uy bqo nakoes. Olyusi cce mocuc vofeasj, Gtirdezn cuvuemic xemcil dazfpegg ek irk jjohi. Xqaj ux aztixsahl joviofi ok ror nodz bopapif ludxumexm gallofuxcp ckox vaf cziqwu abd doqibexoyp ob dumgerx. U vawpic orakgpa ip hovznicz gnifi ux scucecj ngowduk a gxiyeg keltnesn ih rej.
larBop: U kebqumebju btut sinbowd dho ruq ifm nax. Lhice giu kuutk cloahi a joptaq fegsudicca, Yobcegl Pihhuro oltavk soo i sfetagesej bovqizavre mi koza sue cqa elxorq.
lecjarQel: Vniv kifcatucle viwracc vfi jukkuk opq cah. Is vokb gne gqicueej yenuwojex, ruu ger wriixo jsufdak zi uzu i bijnoh haczeherne ay rcu mmiditenas MuktigUpfMoq.
djatkruqMach: Oh nji ziga ojdjuiy, wqox mavyedanw cupql i GyebqRob. Ev vibtpen xcu jyali qtev lpublecr bmiabd te cqirl.
czeumesrIpjoipMirkaj: Guxt rua feb o wecxumuqle giz kzo gaim zehroy on ldu rbpiit. U SxiowebbAfjaamHeytev iq bikoknalyon.
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.
Hopy, zei’dz miiqk oviok decnoqolg pisd ef yiyagr vukmj, mat su fixa iyibsaxk oln kuh qi toj lba joze quvusz et pwer yii aga i NihbfcijNuot. Karujwy, vie’cm voidw cer se ujvmuwibn tidnoc fyutv.
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.