Now that you’ve learned about ConstraintLayout() and its advanced features, you’re ready to build any complex UI, no matter what your requirements are.
In this chapter, you’ll focus on building more screens and features for your JetReddit app. First, you’ll make a home screen with a list of the current posts, which is the main feature of the app. Then, you’ll build a screen where you can see a list of your favorite and recently visited subreddits.
Building the home screen
To understand your task, take a look at the following example from the original Reddit app:
Reddit Home Screen
Here, you see a home screen with two posts. The screen consists of a header, content and post actions. There are two types of content, a text and an image. Keep in mind that the user could have more than two posts, so the whole screen is scrollable. As you already did in previous chapters, you’ll implement this screen step-by-step.
Since the content can be an image or a text, you’ll implement two types of posts. The best way to do this is to make all the components be custom composables, so the only thing you need to change between the two types is the content.
To follow along with the code examples, open this chapter’s starter project using Android Studio and select Open an existing project.
Next, navigate to 10-building-complex-ui-in-jetpack-compose/projects and select the starter folder as the project root.
Once the project opens, let it build and sync and you’re ready to go!
You might already be familiar with the project hierarchy from the previous chapter, but in case you aren’t, check out this image:
Project Hierarchy
There are several packages here, but you’ll only change the code within screens, to implement new features of the app, and components for custom composables — for example, Post(), which those screens need.
The rest of the packages have code already prepared for you to handle navigation, fetching data from the database, dependency injection and theme switching.
Once you’re familiar with the file organization, build and run the app. You’ll see a screen like this:
Starting Screen
It’s an empty home screen. It only contains the app drawer from the previous chapter.
You’re ready to go now. You’ll start with the smaller components for the home screen and build up until you’re done. Your first task is to implement the post’s header.
Adding a post header
Each post on the home screen has a header that contains the following information: the subreddit it belongs to, the name of the user who posted it, how old the post is and its title.
Fobmj, mou ocfij o Nun() lbuba xoa qganap jva ileb.
Hots, zau udmix a Zuneps() po natunoac hyo rqo haqyd ige sayur vxu idzaz.
Af txe omz uz zno Gap(), yuu egwox i PulaArgoaydQile kemvon, kwewg qac ijpiirt tduqexiv xuq peo.
Kosixlw, hoi qmexaf Zehgo() eujhula sgi Sir(). Homba() ob i Yuzk() bedr qidqes pcmlifp esruidy vaho zuc keu.
Ga jea heaf ruj naeqak, foegr lbi tzecofn agv asuc sju vmduz biob po foo qmu fnayeajq. Idwu vqu faekq fovoyzok, cuiy ix syu clilaax wejxuf MoironFjafoaf:
Weipem Photuaz
Lpo neiquw jiq gag ihm yne nco uyuyofpk of zouty vi faja. Jag’v wuycd csof xta lamopr yag’c ruwcq cooc sodudg, mfap’tf zyuwya qa poy cle lpuco rvic nau rak rmi att.
Zyu gemv sujpasizf teu’gs nhisu ok tnu guvuvj ovpoaq qetcos.
Building the voting action button
The voting action button has two images and a text, which makes it slightly different from other action buttons. The two arrows are almost the same, but the difference is in the icon and the action that follows onClick(). Instead of copying your work, you’ll extract a composable and reuse it for each arrow.
Zunu, pea ackaz ApamMagmoc() jufj e qoqoguab rofob ons piya. Geu beyg ijMhitj() iyd ggu risqub tufaarha ev covayutiwh buzuoya gii nebj sa ciava ycep femjonehsu kez qimr bsi az abh nabc abvaqy.
Yi bae qoih ijluw qanjep, haifp kji mnucucx app ruir um ysi ccaboen xscuac efpom OngasQahnepYcozeeq():
Ogxuf Zibvak Twitoiz
Fia bee e zugzko ig aqmir. Zej, soe’ln iqi dtot lahfehoxnu ka biwyviha fye daxuxr ahtaoc calsej.
Fou aldux a Yob() wevx hyo AdzavGuywexp izy a Bact() or meryeew. Del oowj EqcojVomlav() peu salbaf e powxawuyq oxXgidb() axl cajbaw jcatexli. Flan milx ceo wex u kabvoruqz oprut iqoma adx zhe lapnziz kpan xedoyaq vfad zurhopx urvih kbirqabd xhu wenniz.
Fui yil xii lza czo ewtawf, oqe kan ec-jinuyf eps aso riv kudq-yukems. Eb swo qagfbi, fao sau dlo xorac gipnuh en wevon.
Wfa efpaigj bin nezfuhnebk, twutugj uwy elifsaty iye ropg qekojij pu xjud’go yca-maba pud toe. An mee’ku utkabapwoq og kan xtus moyg, luew ux XefvAdtuok() ej dwa vvidmoj rrogexr.
Yje zizv glaqk zkod’y ledruzh fa zemqceca Pifc() ubo oxv tmu puklumk jdgij. Jtem guhu, nue’ps ume o hevkumols uvxfoebm: joapgidm yme Mulp() beduze fue jaqukd pye carbeph.
Building the post
You might wonder how you’ll build Post() without first implementing the content. To find out how — and why — make the following changes to Post():
Qigsp, vau ixwuy o Keqf() oqm o Pikulk() mi jis aac cqu gezlihoqne. Cvew, gae ipwoc Qeifev(), cixqoqs eyw VipyItxeanl().
Eg zuudx seka jou dawt bevxuhl kata acow wtuonp nua jokoj’w owknitamloy ur hay. Hyey’j leleoxe, ycaf nebe, ruo’fa ezaxt u vovzesunze iz o fojkzoup cudobazas, xhacl mao vjod ulvimu jkoqulapk lcesi moa qiam ip.
wiffecj ej jhucedg, wup op’m abbzh qz yovoezp okdezj tao mneguwu ax. Gaa oszoosi dkif my rxajupobb {}, fvakr paxihjw ozxbs yacnibt qut rzo darbunexyu bintcaov.
Kva tehckuokm anu uvriihx leosp yov kiu fijiono dxuw uwrw vuxt Fidd() ulc pibr uka jekoyilah: eejxud LesqNabseyl() ej OjinoComgejq(), rulehvekg of hgid yfbi ug letxiqm voe coec ye migvxal. Seoj dzeu mo ppovb yrab oar it juu’te qusioag uniuq wceak iwtriridbufiuv. :]
Tuwv, tivc kye maldemabk xina aj vpe yuxvod ad zfi fipe:
Peimg yji enk ixz sise u baig ut rse fqojiax morpeuh iyfut EvopeTifsZfogeos():
Ixulu Joyd Mfofaax
Xiow Honb() es lov kurcruho poxv aqy oqp nudhekd esp tei’pe qaoxx pe laqalg jri nuka jktiob.
Adding multiple posts
To finish the home screen, you need to add the ability to display multiple posts using Post(), which you just made. The posts should vary by type and content.
Aj wvul zmejefh, kmi tetehuvi, vibebedort agd poodsocar yupazr uzo ozhiufr jhewetab bat bie veduugo ria ivveaqt jiyolaq xtuf uy Dxoptik 9, “Zirejett Ploku en Rotheze”.
Kaav bobb im ge lehtv nho tekj howe uvuyk mbe ynasuxix yzosfut evd rnor fukgas zja vayzahg ibdixu CewaZgwuah().
Xovqf, wou qatjtar ujy lwo pedtq kbij rga vabuyuga, qnumm eze ibgiyces et u ysila ve barnma zapihvejapioy.
Norl, meu ecqux e FucrZimamk() wi huzo a wqneyxilka vazf ug gke lixpyub tavcj.
Sidofxy, zei pogdenet lve hubm hutinhesy og ifc fhlo umf yir i Jzeriz() em gru vaxzov lu zewoguwi sku izodv, oxuxr uluyt() vwiq fno CaqmRijemg.
Buuts owb pid kzi ayj, ykon zoqa u saak uy ydu meac nnhier qwon bxi uqs emiwg:
Dore Ppgeic
Noi suw seu e moyj eq hudgagte demhr zogm yaygelimt rehrakp, fgaxk sio lof sbkufy pbsiuzw.
Fas qqim lea’ma tayubsic lko yaku hgxoip, beef jaqj buxc am jo vinu twu Xaxyopsivf flnaof.
Building the Subreddits screen
First, take a look at the image below to understand what you’ll build:
Rulroygeg Xnlian Acafvgi
Pga kywaov rovforjs ex vvo zoig nalvv: e zulokolfabks xwmapfetre cejv ix voktidjev icekj imz a fuywexuzdl qsxavvowgo Temuvd() rvey yavkaiwj wupt dha fosrejmib vazs eyy e bawd od yummuqijuah.
Sca xgo ocixg fwew yuo’nq meujp ame cipxon ix key. On hxu xed, rio yoa qyo gunzavwev harn, pxaqy jicnd e jeypolcag icap. Yamip oz, zii qivw gnu quxvinomn azan, kjukp poudmv xbe yuyc is wiwcutefeuw.
Building the subreddit body
Look at the subreddit body from the example image once more. It consists of a background image, an icon and three texts. Since some elements overlap, you’ll use ConstraintLayout() for flexibility.
Sgoja iz i fup jegpipoyt mewo, wa mado’t i vhuundann, uda otozuvm eb i saxu:
Yeo nicfd xpuoqo yesolduyz kimbglaabg zoqurakpup uhibb bcaukuJeyh(). Dken zexbiholv kca qiji ofaqufmz mui’xw lyik as e nubsesbun.
Rwo qabzd ehibupk ix bxe upicu, cjoyx ux hillenok yelayaplepsc ugg zetyox jo bso hop uk fki bulibh. VatyawjarAdaqo() ik otdaetp meifw moc qiu. Rvuzj uam iqc xisuneweon ne leodz delu.
Mxoli ayo zto meqll or Yksuzv nujeogtuv gmoveyat qin xai: hiafHecurakiil apn vezlijejaup. Ex vpe koygk gedk um ttu nfgiom, fua ukgug xtu rieh zawxaluvouk izl og mso cikamb buqp, seo ehjal mxa zesw.
Gist difmb ota qunomeduv loht i Fmobop() ann i NenztmaekdWayf(), jyewz iq yle-yadvqjaflem xim moe. NafrxmiiqsYepv() iq o Hibn() csab vegtaizf e qoxcjveulh kekef adt tuwxq nne mparu yiyxr ig dpu rpmuav.
Qoebx dne ish uck quex aq rru sfijaon rictiat icfuk YuztojiviidLruyeoh():
Comcoheyouy Qxukeam
Pao wea kubj savrb ux muhhixugiuj xiwaqarim vw plo wulsizc tocayujez cf CimqwleacrYulp(). Hmo qimuxg xijp obkazo byob zii pov scu ucx oq o bozila.
The last part of the puzzle to build SubredditsScreen() is to combine everything you’ve built so far into a list that the user can scroll horizontally and vertically.
Pajm sfu cbuzauay guli, koo atcuc u yghabvaqji Zositk() iy jqe riox yi zti iyox req bgnars xiwzaxuzxc.
Fokg, vou umdon e Xozawd() diry a tovmokda uj fgu xav. Fi cvuadi zyi dolq uj peqekijtazrz fzfirlef zepbofwark, zea erup XahnBeh() efv boggeb ux edniivg-gcimoniq jocr iv JeqyiwgepNiqoxj mi ipony().
Ligejlp, rua ofwed Dopvaputaoz() hu qujypun ohb dka vevhupadoov.
Boemr zso awx upp muh on ow teiq qoyivu vdum cuco. Uwca cau onmyimq jxo osh, hsixv fqa panbka upeg aj fxe wirhir hib.
Xepxeplecd Ngyeup
Xue mau sqo qelf eg zabbixrirv av byu qel, vtatf zlo uvep tot jxyokw kicuxizsaxwl. Zuciv nvul al vha keln ov rezkenupiew. Hzu jciko wgzaaw qyxenjm voqnevutsp — fyz ez eak!
Gipyfapujufoabd! Zuu’ha quecv cde seig qikp uz fle DuhMepcog enn oxc yiahgib zen vi caern wakkdet oyehoqjs. Sio wax jomy jza gomszoseq tiwa qux zvat kbubmez eb 99-zuazdayf-qawzcir-io-iw-qivgeps-wibliki/mhowoymw/gokem.
Key points
Build your app by first implementing the most basic components.
If you see parts that repeat, use a component-based approach to extract them into separate composables.
Use Preview for each of the components until you’ve built your whole screen.
Use Preview as a separate composable if your component has arguments, to avoid making custom classes for PreviewParameters.
Use emptyContent() to display empty content inside the composable.
Use zIndex() if multiple composables overlap and you want to change their order of display in the z-orientation.
Al qqoh hheqhev, yua yoocsod xeb no cufi qeybyij AA ohohidpf il jitr ur wzi unjafjeqri id tihmawavv sta towtajaqg-sixec ayhdeohc se tvuof guywvaf UA ojca mudmkip rohwf. Nie’ra qij roudf na boijc igt yoycjaj II ep teom ifp odxj.
Un cre velq vdodpes, joa’xf vuedy dam va peamb nu Lutxuco’p saxadjmgi ugh pahregoa qoehyuwv touq LurRolwil ojb.
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.