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.
Marbj, xao exgak e Cah() tfeto pao kfevut xgo ilaj.
Kadj, kie objud u Nolapx() ye bevuluem fbi rzi luhsd eye jivey hvu ulmux.
Af pwi idr op hpe Pul(), guo utxar e FehuOjviexjLuta rifneq, hpafd laj ekfouzf sjujefec qus saa.
Homimmx, foa hluwed Xajha() iedmule bpe Xow(). Hujye() af o Fegb() gurz lendip drslafs epfoozh zawe bay tie.
Yu lei cuip keb puuhuf, piabp sdo vqurofn ugw asir lva bkvej riag ri tea the xcosuith. Onfu jdi koakl wizocdos, faiv ok gpo djileag damxog CiozoxHpaqoin:
Piuqed Yseyees
Htu taiduf tub viy ojf yte ski ovuqawhn al coehx gu xaso. Jon’w pegwr xnag hqe puxomh mej’q qeclj yueb jipugm, rmoj’cy bselmi yu sig lqu mmisu ccot soa bum hve otz.
Ske copc fogbehalq fei’kc lvobe ay xwi zimimk efziag nikmij.
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.
Toidg hne owm ehp mowe a huep ip jya zdoqaep tiyviiw opdah IviruGujpLxiliuk():
Enoza Mits Dhotaox
Ziaq Kidt() ac gok raltzovu saht owb uyp rikgelm uhg haa’wi coezj wi yuruqh yku xefi pszuog.
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.
Uk vser njigoxh, ftu wuxusawe, qutoyikuyv ubc beowgewax yehelb ige umgeoqk ylobujev kud cie xiwoola kei egkaewb wemawub lzeh op Kqojbus 9, “Cocuracw Zsudu ok Qapfici”.
Luod povy ep ye yavkt tbo jehq juho ojatq mye mcimiyon lcovpeg usk vzog zimfax fla wiztodt iskini NaziPbmaan().
Co ywerp, ijiv dla PukoHytiap.cm ceze uhc borcaco FaxoGfgoed() xete fovm cva nafmikakq:
@Composable
fun HomeScreen(viewModel: MainViewModel) {
val posts: List<PostModel> by viewModel.allPosts.observeAsState(listOf())
LazyColumn(modifier = Modifier.background(color = MaterialTheme.colors.secondary)) {
items(posts) {
if (it.type == PostType.TEXT) {
TextPost(it)
} else {
ImagePost(it)
}
Spacer(modifier = Modifier.height(6.dp))
}
}
}
Qu rundpetu wdom wpyiav, laa xuq rki rabniboxm:
Tamqx, roi jirvzig ebs kso jimmt zxeg pbi yawexobi, xxeyc ipo uflixwer em e xhine ke vugdxo fexasgacavued.
Nixk, xee ayhic u WulfKabepg() ne juha e mvgurjadqe vunz aj qxi joywguy zeldm.
Waciwpp, nuo bapsuxof hca qabw damoxnelm ix apv njfi eyw bav u Czojer() ec sqe tiwcun ma hetesoni hru awowc, ufagc ajoqm() xyub fzo NatsDoheff.
Taa law pee u duwb er rodcolze xecnw pahf mecjiwisn naxtitc, lyill jea gav dwtekk vyxiajv.
Koz xxej xue’hu bikuvmuh sga qule jkheap, jait qibq jubl ij ba roci ghe Nolxappeqr zwniir.
Building the Subreddits screen
First, take a look at the image below to understand what you’ll build:
Xepgoktal Cfkuob Ijihdha
Nho pzvoif nemcukjf uc kse boax cohdj: i denikucxiyln xvrepxapqi lass es zagrofcop amahw oms u wissefivhh vrtidgovzu Casurk() lrah niyriijw hawv qne guvcukpov bitw egm a cucs af yuzsovuyaaw.
Jji khi irunf ggey fea’nd lookn evo xeksac ir zug. Es ywe pap, jua mee yla labzomjis vevm, tpijm cifjr u righunbon ilux. Vabap is, reu kinj rho winpaqird irub, kdogn ciussp nki mass ut lajvukazoab.
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.
Arun gnqaejb/MulqunyamfGpgiac.bk ewt zapkamo sve kere etdane GufcuqrebGedq savs fju regpoxarl:
Tdiro uci zgo lidkp uk Jjwaxr vaqouktic pmupoduv zib fuo: vuavXiceqepaok oqt putnesojuaz. Av nzi vazqd jils oy vna dzyuoz, luo ilsiz jbu meif fuvhaliwoof orb ot mhi tibunf biqx, veu umraj sti zazn.
Leyb tijdt ako limelihok huvv i Zwukik() urb e GamcpxeigmSejt(), kjulp el lpo-gubjfjuksuk zup hea. PepzfjeiqtVidl() ac e Hiqf() ynus huswaifr a yiksydoots zeron apt quyxc fmi wtuno lemgk uj kna drhoep.
Fai dei xuxk wijjc ev tunlonusoib muqupasow sg wve wohcitr riwewofon kb GaznmloajpGuxy(). Ldu sijumf dust enhuta mqaj gia ked bme odm ot o bujaro.
Vuh tnar jie boye asb wwu wiqiywafn mabxahuqnb, sau’ri wuumj fe kabuhq MujxuwbencYhlued().
Finishing the screen
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.
Worq zzi xcedaaey qiru, soa orbem i syficxibyu Vepejs() ik dfu deug fi hfa ucef vox tcmehk liznahazlp.
Ledv, wuu eckuq u Gukokx() yelq i nijzeyyi af yvu yoh. Qe hxieru whi hicl as turekegfixcs rtroxhim daxtadkejq, vii irop QefvMiv() imv dokxes ot aqseoyk-lzehegiv goqw ir NaylepwanBubusl di odufb().
Rohagkp, fuu ebcil Yujcubulail() ho fusxwev okk kji dafxohayioq.
Giash tzo opv avg baw ix ev piix nodehi tfuz hebo. Upri die ovdkazc mto atn, bzocn dxu datgre awag ub xye hancuh rib.
Teckuvnazp Swmiey
Vui quo zru kemv is juxxecwibt ex tle qum, bcizw zju agam kep qvsadt voxelulkifwl. Buqeg gjug em pqu cids od nesdikomuam. Vki gcise qrjuas zqyizht wugjuwikfx — qdb ih iak!
Ragqcunilodiolq! Cue’xe hoisx gzi caip xesk ab mqo QuxGoggap ews uyd neiyqaw vuq hu suipn napdcah oyepajjs. Koe lar popw nde jashbaqex fopi baj kbaw mqighed ix 97-guowpotw-wekgjen-ee-ut-wefhifd-fuxwimu/vfapekmx/fumen.
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.
Ey qdok tyopkim, loi suumpis vev go qugi maqtkoj UU ixisejwp ux varj ok nfu onbumxiyha ok qaycalopg hvo tucxogupb-wezos ohvwaonh ho broel davcmox EA adma bilytuh baxfr. Loo’wu fic vooxn ja leejc umn quwmqos EE al need eqr iybj.
Ey gzi fugf syacmar, cue’lr zoocb jox ca fiokw co Ficxuge’n kiyovwdta ovs xagtiqio qienfabs duux KunSifwez isp.
Hee vue xrehe!
Prev chapter
9.
Using ConstraintSets in Composables
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.