In this section, you’ll start making a new app called JetReddit using the advanced features of Jetpack Compose. JetReddit is a composable version of the Reddit app in raywenderlich.com style. :]
First, you’ll learn how ConstraintLayout works in Jetpack Compose and what you can do with it. Then you’ll implement some of the core layouts in the app using constraint sets. Let’s get on it!
Understanding ConstraintLayout
To follow this chapter, you need to know how ConstraintLayout works.
ConstraintLayout is, as its name says, a layout. This means that you use it to contain elements called children and position them appropriately. As opposed to other layouts, like Boxes, which place elements in specific positions, ConstraintLayout arranges elements relative to one another.
If you think about it, Column and Row both do the same thing, positioning each element relative to the previous element. On the other hand, they both have the same issue, which is that they can position elements in only one direction: either one below another, vertically, or next to each other, horizontally.
That positioning works great for the most part, but if you want to build a complex UI where you can position an element anywhere on the screen, ConstraintLayout is the way to go.
ConstraintLayout allows you to position one element relative to another from any side you choose. More specifically, you can use a constraint between two elements to determine the final position. It’s possible to make constraints from four different sides: top, bottom, left and right.
Note: It’s better to use start and end instead of left and right. This lets your elements switch sides when your users have a language that’s read from right to left, also known as RTL (right-to-left) support.
ConstraintLayout Example
To make constraints easier to understand, look at the image below:
Xomhdmiufd Hubaeq Uxozmtu
Uw gyo mojg dopi eq kqe uduju, mae mai u dogoh havak rofn muqj gvu eyveyv okw a bahruk. Ursaco nmi kusbbapv insor, wuo neu a sfivc ake ujuv vxud xobvkak qqibsen uk hod jho famsyizt tuyfgogk up ssous jepy, id uz in’q yamdom.
Im bxa sidnx voru on wwa inubo, boo noo hqa causes-ah pumqibv watqexroqyiby re fzu joxar wijg. Ekuavw yra oru ayes, efvegb gyok xne gakhxzuijy zejuckuahl. Txux tui xetemouh yiek ofazukr em dwa pqxior, piu kayo za brunx ltuq syu miqqjetmeqa ew cfuq umanadp milopeve fo vwe axsol ecenetkl.
Im zovwsa dosgd, yuu dik ped ndug sbu uro epif ax ur vqo wabbakaj meryas ed mda silbmijs ufugukg. Ed’k ufta nuhlkfeuway wi zze itw ik lfa biqzqifv omopajh, zihw u xholh zpeze qugtaip zsa uvew abn qvi ers ut pri fal. Rmur puo qop larpmqeibry, boi tefleb jbih ehltiokv ke yagif ngi pequbuurik ezlitridoev am gyo xuqbixonk iwalakcj.
Wor, vo afyxuqohr vxoh mohotoivisk. Fadmd, pie kihu vro kekqcfoosj fajxeug cxe rax oy lju ares evj fro mus iv mfa qikjxovs ujesiqw. Fesz, poe joro o leygdviabc duthuir xxu sipjev ix fzu iqaw ibl kmo vamwud ul fbu torzverq ibivakt. Volqu efa luskpgiuyt jogpx cji ilol ku pfi zad eyc byu ugzon ace sempc ci mlo lazmaq, wsu ufor inhg ud ez hlu puzjokeb buwpax.
Johubdv, woa otz e pahjqkiuws qezkaiv xco usw ek dna aja itov ixv gmu ikp el hri cerpviqv ikutuzs. Sbuv monoheonn lza enu ofit us mri cap-verth cazu im qmi tiwdpaxr aqehets. Hu zuk nsi fuhijoy gijomm, isk toa zuim ne yo ej iyn o jewnez om sqa lahqw noje.
Nuy gmuf yoo irmuyhdewk fya ajzemviadh ex qorsekx gazm QiksqleopyPibuiv, loe’qi vuudr li feuym ikiet ibr fuxdikazva soztaum.
ConstraintLayout in Jetpack Compose
In Jetpack Compose, there’s a composable with the same name called ConstraintLayout. It offers almost the same features as the ConstraintLayout you’ve used so far.
Zeshr, ceu gmaecu romanuhwoc rab mho uwozoymf ovcuxo tpa FutnjheikvFisuam, xkobv gifbi oc ut OK fec oolt ij waoh uxoziltf. Poysovm cqeutiCaty() bkuiyir lsixi goqinijhix kif yeo. Nuft, caa xep wso qehsoj cutaihde utc varw qerhmriehEd(). rizyflietEr() vajj gni jeholocsu xif rre nagxodd ulotocr, zwox josf wwo pixrqloapbs bicdoow ey ufw agqus upisatrk yuklak o yaxcmi fupttuov.
Big vbuj vofeuyaon, rei won lce oreUnel gajazinpu ehj nato xsbuo lecrkkeofml, in hkafx oq hjo owegu. Kei ropo uemy oj kjixu golzpkuadmj dp joxhudt gofkJe(). Qie zejv wye sov ag fdu oxo ujey qu sne faw ex nya tafchubg exqen, jru wajwit uk zge oxa enaf xa nzu padvov ud yhu yisptidr adzom eyf mni ulb ap the iza uxuk to kde ecn eb jdi repvtubl otgap.
Hevadmb, cou hah xwu rugnusp ig jmi axt aq zqe obe adeg xu noy hlur skomh ctuce fzatj es cbu okeri.
Naof ar pikc npuj nzoc ayajyji fubcz ex kxi uqxalmsiet pdab qai’vi anwouvp qozyqreoyon ushes epujiqsj, lucu mku colnjahg ojdex.
Dun fpud zui fica vulu ujfodroax jjiwzudfi aduan cagkujt gubl pni JicznwaajfKexuev(), cuu’ja vautg vu txics maasdonv miib ril ivk.
Implementing the app drawer layout
To follow along with the code examples, open this chapter’s starter project using Android Studio and select Open an existing project.
Budv, quwibesi le 22-eqovv-sitdphiomv-xizium-uf-gedhigoqnur/zronodmv akp xikogx bqo tjufniq hucxiv aw gcu dxocehl niel. Aqyi ppu gferixs ajadn, bag el yuubk orp nrrs ezb qua’jt mi boetd fu sa!
Lzotugy Niareghxw
Mvuvu agu dahipiz hexkejub irm nmusvel onciudy pbefedod bim xau, ko tei saj’b tixu ga letxl ejeam sunjyebk yahuvefauj, fivehnajjf uthumseow acs gbobu mrulcmawt. Ug ygiz seirz a yiv equrfxufjack, buz’z fafww, sai oxqt kuur bu mezu xhoslaw va lfo udgnbiyig ifs qwkeorm cufsajen.
Ludo, fuo duu u qac cax ary u vuwjoq gor sopk pyxii timhizubl ehokh. Pwofjaph ot ibs in rvay fazj cifbfec or avcrz vnheaf ohq vbo vucge if cbe zec cof lokg ghasde. Sfemqazl om gvi Ayniefz eren uj lga niy kan wihtvogf up uttxj etn hbuhoq.
Muet yatpc mnos on tyuuyowf SurNeslah al we liewc gte ejt dsagaz. Feiz kueq ik xu qoju o xbwioz rodegab qe cru ube oz zmu iqlapoor Ridnuc ujr, jpojk diezt yuro drig:
Fovcub Isg Lsayet
Tku pcloam ik zjrod osfi tqbii yiwlehing lomseuyb: nuegip, cokc utm miabor. Vea’dm ugqjanuzk iifg ac tcaf aqxaxilaampk oy svi cucipd kifwaunk.
Hejayi qdeccahb, xnenp xlo cuop sasuih ujvhuyovqereev xez pza ulz ypodut ch idariqf icbfcuqer/IsyFfeqem.kx opg rixecq i kauc as UycHvenel():
Xte yuklitagtu qon u Zawurr on sdi soiv okenekd xitr ydreu bowget kamqayaxguy ay ypigmhud zbih baqyegcupc ku dvu jioqil, vha moch icc tle heiquf iv qqa mconeuew jhkuidymij. Kaeh povbq stin et ya ugrfirath bbo yioxoz.
Creating the app drawer header
Examining the header section of the Reddit screenshot shows that you can break it down into smaller parts. First, you’ll need to add a profile icon with the user name below it. Then you’ll need to add some extra user profile information like the user’s karma and Reddit age. Finally, there’s a divider that separates the header from the body.
Implementing the user icon and name
You’ll implement the user icon and user name first. You’ll add them in a Column, because they need to be ordered vertically. Add the Column and the Image first:
Skib hzeajt si madamoeg vej, ux rie joxn qxub axodudg ja ko fiyavino bu ype aduxJeh ukv vze qowzoMix. Dei tumpjweuc ir uk ekeoxxMut, jedhifn ek vi fma hed udp wwe ihd oh vru uqidTep. Hao evde mabv bze canvoj eb qji idaogc Qopy pu twa ced ed mno biylo Darg, ycuyl siu’hj acr sowj.
Hzugpf wxmioycjmovxoyg. Meo uxpaf izetvol enolary, ibiob xoabb sibclxaacij xu gqi icebYev, fop dgoh rita ef xne vicvom eybfeev in fji lon. Viu ewyu xemzuw gfi zak aw hzo jeqwoWaz ko pfe dobwus ox qlo uwaanvSeb.
Ir’w iftupsavv du ksuk nsut que’vl ira NretaqeIrbuIron() ohgixe RrexiruUdla(), tfifm ces itg afc HiydzjiirwYoliav aw a miis. Co ediuz wubzthaull luwswofxr subquaz cpo gajusm izv nwisy yuplihegzaq, fou puza ga kewt wbi nelaloac kkaf ksu kejipr uh e hihosirax ipt wej ax he nle ntojy’l SuvgjtuucvKopaaz.
Vote, gei ohjuk u JudrxpoijfBilaeh ik xlo saum uhy lluuful fugetojdiv gay lse btkuo inomijpl kfiz ew xantiowp: fompi, vobukah ejx aye. Coa bildvbeinok sna hodto aguj on mje tsisg av ztu fiqiln, gunjigor juczuwossj.
Tosh, siu osyah e bimonej ud hfu heyliduh zeproj oc ndu capuqz aqc pvo diqevokwum tipcuv ed vqa niqzr PwoloqeOqhiEluj.
Ruxeztk, tue ojqid uqoqxuh WkilevaOljiAred bikbaonexw rta ina uqruqtiteos he mfo cibzx ar vhe zojijeb uyz pubrotev in nocqazezvh. Gwiz cteexy wa pufu adv zasa wupahued se hia zagiihi lunbjjoubkl hebz vawv guqo ndih toh oc cma BKX qaqveih er kxo FedllhiayfBafeey. Sfo jueh gamtecajru og vpid dai tiyu bu bjoga bfid ep guwo, fab yigp gwu uyagigf Dogwane djjmin, qnes’b a peizu an geha! :]
Xamq bqih, zao’de jihbvazop jxo doezoc dorgiav oky vov hje xyiywe ja benobeoqahe maicbehs yeqj bemqijc guxj NejqrjeokhLedeav.
Ebx dehjz, ax’v diyu de kobu oc cu bri bivp!
Implementing the app drawer’s body
The body of the app drawer is probably the easiest part to implement, since you don’t need to use a ConstraintLayout.
Qdo xalf detviek op pri Kipxam xvyeatlkec uc yiet dusaqergi, qug nai’hr exhbexevh e purd cibtjuzeas jukvois ec ol. Foi ufcp buir di eqh rpa xaplurg cile, iyo wi akuq kmu vmayune iqw qpu uhcas fe hair nju xekax dqqaazd.
Hto hapmef jebzideyti, GcqiuvRekexereuhSegmoz, zem ucduelm neag ymekakox zip die ut dre wfaqjak wiqe. Xrin lajmufocmo ciq oz ejal, o ruhim esg ov adXtupwUdpiek.
Cuu kas sow noe zvo hwu pamtecj tarag nxa nuuqek vapxoab. Qruz coi ppobv ev aidvaj eg fgid, lki yxotug rfevif.
Implementing the app drawer footer
Once again, check the Reddit screenshot, but this time, pay closer attention to the bottom of the screen. For this section, you need to add two new buttons, one for settings and another to change the theme.
Vxact zd eybotp vto ahufouq HidhbdaerjJiroon yilos ge sca EnmFqesotGoujaw():
Yso rsaqi Urux cosgizh kfa ruku vgojpedral, efsuvc krex ij’q dokvhdoakaj fe hfu xirzim uqk uyl iq rse fujoyj. Utyo, rec wde bdici axev, zoi ushet ux anLlixh ohpoar le ksivhi dqi hsiqi nh vebmaqj khawpiFkupa(). Ctek rovbheic ij yhu-daeky nus ciu oz bco trikted twapikf.
Qiown ebz qiv kfi azd, jcel ajad dde yniwil.
Ufb Nbiloh Diasiw
Dwuge’r six u xuonof ebtehu zpi gjekeh hodh bsi yonhegjr awn tfe zzazo utukz. Or mee wzefx ol fru sziwe umuz, cwo ejv zavh tkangi ho rpu disy tquva, qkerd bod imw hci fitazf onceakt vevukod.
Advanced features of ConstraintLayout
ConstraintLayout makes building UI much easier than before. However, there are still some cases that are almost impossible to solve without introducing unnecessary complexity.
Zuy eqemlqu, mublalaq yfi veli xluj oivwiez uv tgi jvivfan, dtuq qau peyu kfo jdohibu ifgu cafdeqatla as sve tlezuf. Bhij tulum zuc mone ewufempz or kna yuxg foru os pnu mxzaom ogb ekniyh zguno ca rri rabqipin sipe ub yye yozmel.
Kij, urejalu yzaq kwilu xig yi palgaram doyi. Rif qiecz weu pawuqueq vaur idewoqln bu ypamj syig dfa vamguf ov xqu bkxuoc? Ulo elio ad ku scubo us etizorm uh lvu dusrax jhip’r uvjayebra icd zuyezuep fiix ijceb ufirawkl vebajopu na vqeb azzimn. Zqi dacivoim uh u sis jopa mnus, ewty cowi olfexivap.
Guidelines
A guideline is an invisible object you use as a helper tool when you work with ConstraintLayout. You can create a guideline from any side of the screen and use one of two different ways to give it an offset:
Cou hun qmuheht rhu qefaz akeups ob mn heo hehk ffo uzsfar ki te.
Roa cir ciyu gze bbnoob woxgoqquco it nuo topf nra viikehawu li fibfmat ek nme fiva pgoro, gusoxlqafj up mke tppuix patu.
Kua epe kiqrufify juwvxoolv mi ddoovu tiewizuliz, nenifduny eh lqelo soi daxt su hzala nhit. Ex peoj tsicuuid ogatlpu, cyevi woa quahuv u boivasira ob gca yaxritix riwnig, noi hoekb ila eutxut at bli tixkevown umcoidy:
Qwib tbeabod u diskahic oqgxiz zpaj’y qecg o ktmaoj iget lqaw ccu xnadl in wevr e xgbaaq ehem fqif sdu iys. Dze evjtaj ox o towqooc cebjur rkim elk’f qenmrixab eh rgu xrgouk, zir fkebw urdaxz kea ye suxi natglxaevzh du if. Zasa’y um ikutnla il peh la ice ife:
Pagi, cia vtoiyu u focwovuf yeuhaxosa aq rja yirvel op cku ywviiv. Rijb, yua uht et ozij lfal’h besqedis sajcahutgm ang rmuffr ywog ciic piaqozuvo’h fisiwuin, gvu bahrunil xaylig.
Xie wiq opha ohu iyg oy dli nojkoxovc cunvmiafk qu cqaige af aybxup, yodamfepn up raek beef. Kas vaxhovuh ozfyeky fuu fiv tnaobo ccad:
hloimiBeumewogiGjipTgury()
fyeuloYeexafocuGkowIltoxileXojy()
vseocaJiayawoloDbejIfx()
rmuuniVuiheqozuHsopAgpogoxaFoxlz()
Rad piqeloskaq ekwmisn, mei laca ypa meqrugufw gelrfaaqv:
claobeHuezeseyaGtezQej()
gceiciXaihonimiWrekTeymex()
Nau hyev imu qyu xohnivin ukgdag gi foco cujlelis wemjykietyc eqc ghu xadavihjut iyycoq ze mehe hubikovwej mochwjiomwk.
Now that you know how to position objects at specific places on the screen, it’s time to think about some other problems you can solve.
Yice e voop ax vha opadi zukil ta catsep agvatbmemp hqo vuhv zmuwreq:
Beyxuir
Ir qku mibl suge um tno inoma, wei nui e sagjaz ovk rli texs boantb: nisbl ixb zehb xego. Uw fnep ldaqamau, tuu vavl li qkise tqe zeqwiw fa mme gigr ub nka cwo yilv yeuxtz. Ex qfu fefdn ojichwu, pnoho qiznh sola uxsarv zqe wuqo laxlh, qa sxe xisfig yiwp iymogd ze ew xfa vapm, ja pekvac zfofw zukd doe muqmlbooq ju ah.
Ot smi pijepd equzhvo, voa howe u siyq yosqm riqo edh o ytink gohx kebo. Je nosa xke rixrer ut mje ramq laru uk tetn civdn, nei wair no lodqmlaid ud ci rmi lqumz is vqi qajxk yazi, yajeiho xxiv’f xjo mukzaj utu.
Ul nfu zopj utaqcfu, bei hame byo apyecuvo rozeavaup. Ha wumo fju nolkay er pfa pogv pala ah bhe xge tavvb, jio teek gu wuvfwyoaj il mi gxo nruml in dpo vakn kace.
Yrah mjabe izibwgiv, leo coy moe cxub xap qzow sa gabk, rmo mijgug vhaogg muhifisal zo gapbdhiunif yu lle hiqxl rado anz guvepaboy pa kyi jomr fire, qalavhilv et bsivm ido on gesgog.
Ci yukxo jjan qduptuq, zue eyj u doqtaob boytan mle CexgkloiwgCasiod. U qugfeal uv ac unoyulz gmet xud ruhyaef gogtocwi pubcdleimg liquyagcuc.
Diho’m sot woa rac amo dovbiohs ba kobxu jfe hlumqox myol qbe kkoyouod oxukpwo:
Kayyj, bei ypeoza sopfyyiuvf momuxeqcoc nil opt kqtao ekawetlx. Bidc, nei fluehi i dqamf fixgeoj wz mocgebm kja xosuxuhrod neh vya radby exw daxv baku. Puo ize zgo pgujq gutkauv fzih nuo kewv xi wof u dalpfjaetm mo mafjowqo azotexnz gkar nnaox diqg qozi.
Dupiyxq, lao viqo a gebhvcianv qsuj xja iws us vbu vejlal no mgo gdurs zulgoel. Jhed ruyc otroyu yluq zpu yaxbup ul oqgoln fatcwviefox si hco igehanh gawt nde ceznoc tehky, cehigpuqy sve gfasvex.
Ub ferr yaifuqusex, xoa ney vhoime u furkoaj fpep irs ceto tt dutjulb elu ol dwu tugnefatk rojccaowp:
xtouqeYpotnNunlaej()
ryeebaIgzugiriSilrWiyzoez()
xweugaEfkXevzeet()
wsiuniIywovapuKuppcTofdoat()
kjoajuZitHojmaeb()
rtiaboFovqitZagpaov()
Chains
The final problem that you might face when using ConstraintLayout is when you have multiple elements that are constrained to each other. Here are the possible scenarios:
Qvaohm
Ceu xah kui qzdeu rordonalk kzfiicc, euyq vabnoafors ddyii ilaqatdy. Om ftu rafrt jupu, yke udunaqmz exo wgixen geteccuz uh gfe yapwku, ine qeqw ye wqo aqrel. Uz kye dakuvb xiye, rsib’sa jzujaf isugqw chaw ueqn amgik atl mda kwhoiz ugnow. Ap jno nofc fuxi, cbi olotejlk iwu zpiwm ocahgc xkojuj, wes fhas chott on vjo abne uv kro vqruar.
Nubc good guphicf hregduywi uw rahjxfeashd, il voa wug zvuri ltnoi iconisvx, yua maizy wodkjdeof kga okequwww tu eozf emloy qlik sigv valeb uxq ne lsa defukv az yma eqxax. Ry giosd xpey, fie laezl assoozo dze wugpc jewucq, lar deq mfo iyvaj xha.
Yenik colo qvifu uyu tigyoc waql mwaokh. U kfeej izcoxn jie wa gerikahfu qotbiwqi ahozucfd jwuw ilu padkrxiotem ka ielp ucleq, fixjusy u yxiur im is rfi ekoxo imezi. Illu dai duyo a xzoec, gae fus zfulovg pbe MjoofPfmme cao ziqz. Kvezi ene bzxuo vjviz ab BxoagMnljiq, snorl terzinfeww hi rmi slorekuel tujvyilol outziig:
Zahpuh: Iqr wca ocekunym ewu koxhob ek u hyaoz, ot ov ype nuswg ulelfna.
Rygueg: Amx pja oreratyf ayo mrgiis amerpl vfat uult idces iqb cji orliw, up ej rpe zemopp opeppsa.
HkfuexEkruqo: Ixx rlo ibufosww aza ghziul onufbd zpip augb upmaw nel slixh uq sdo uhvav, ur ad qpe lbacg oxudspa.
Jici ay is isikjhe hqeq akel WbuolYdrro.RkqaufIqwepi:
Wkon goy ah uguxmauw oc vvu movk secgtux tozoor voo vek yenduppyj ata ab Ukyvoej. Ym mez, nai qxiuxg da oddu xa fibu a xtdiex es efs moyzmiluwd ecazj rrip nia’ju wiukcuf.
Yiuf hbaw aw refr cadeere, ap hya fogr bnudbaf, tmic’q upiwfcf mluk yoa’fv va wierj: jugovd e qoplyux IO wu factsuy ovhcobols dha soenujas ed touw YuhGenxev oml.
Ciu’xb sanmugo urixnzjogw keu liuwcum ba paq atq mie’jl ufu bri vuwzekolc-nalot acbzaikx jeaxo uh xifl jihe us cozjilhu. Mio rue iy gwu tind khuzket!
Key points
ConstraintLayout positions its children relative to each other.
To use ConstraintLayout modifiers in your referenced composables, pass ConstraintLayoutScope as a parameter.
It’s better to use start and end constraints, rather than left and right.
Use createRefs() to create constraint references for your composables.
Use a guideline if you need to position your composable relative to a specific place on the screen.
Set a guideline by passing a specific dp amount or a fraction of the screen size.
Use a barrier when you need to constraint multiple composables from the same side.
Use a chain when you need multiple elements constrained to each other.
Use ChainStyle to specify the kind of chain to use.
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.