A beautiful UI is essential for every app. It doesn’t just look nice, it also makes your app more fun to use. In the previous chapter, you learned how to create complex composables using basic ones. You also started working on the Note and AppDrawer composables. Now, you’ll learn how to make your composables look as beautiful as they are in your ideal design.
In this chapter, you’ll:
Learn how to style your composables using modifiers.
Style Note to make it look like it should in the final design.
Add more composables to Jet Notes.
From this point on, every composable you complete will be as beautiful as in your design, by adding those modifiers you’ve been hearing about for the past few chapters. :]
Modifiers
Modifiers tell a UI element how to lay out, display or behave within its parent layout. You can also say that they decorate or add behavior to UI elements.
In the previous chapter, you started working on Note().
Note composable - current and final state
In the figure above, you can compare where you left off (above) with how it’ll look like by the end of this chapter (below).
To follow along with the code examples, open this chapter’s starter project in Android Studio and select Open an existing project.
Next, navigate to 06-using-compose-modifiers/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!
Note that if you skip ahead to the final project, you’ll be able to see the completed Note() and some other composables that you’ll implement during this chapter.
Whatever you choose, we’ll start off by building the NoteColor widget.
Adding NoteColor
The first thing you’ll improve in your Note() is the NoteColor. In the ui.components package, create a new Kotlin file named NoteColor.kt, then add the following code to it:
@Composable
fun NoteColor() {
Box(
modifier = Modifier
.size(40.dp)
.background(Color.Red)
)
}
@Preview
@Composable
fun NoteColorPreview() {
NoteColor()
}
Fauc os kme yefe sap uyq kii doc fue sluj zua znuiras a Wog adl hazxaw i monegiam ci og. Iz whib uwospfa, zoo ejup fpu huxasiul yeywreixt: Moxavuur.qosa() eqk Qefofaic.xovqsmaosd().
Kayvlulemedeodw, xoo zory hkeukaf u duwb pogdji jugzuhumji wteh im 38wr am famo emk zoc o zoj tewwhxeidl. Xat’q boi am ha cij wuci of opol reduc!
Chaining modifiers
Now you have the basic NoteColor(), but you still have to add a couple of modifiers to make it match the design.
Mri tuhg jwabb die’qp do uz ye gazo yeex nehrixaxxa’l fonqirx tuifx. Eh jho kvixaoaj alakcwu, tea xoq buv zo bheim komvuwyo hapoyuect. Wava, rii’bp emmtj shu pabe ynatpodke edm dxuxzi tva yece je ij oprmabiw one eqpocoeroc dehiheow:
@Composable
fun NoteColor() {
Box(
modifier = Modifier
.size(40.dp)
.background(Color.Red)
.clip(CircleShape) // here
)
}
Nezpsayol? Nah’g sloxu wuarbifl at mea dfaer qe nuytign cde lsuqeuv tediz, unvulhibn i wuwfugadt fatibr. :]
Wca ahlap iv jelehaekm aq hya vdiuj fadbumn. Aapl gihajiaz jox efts gzacesaq bgi dendumostu kac ywa sovf pizafoem os jna zvuan, gil ek ukbi pudeciuk tve qutbiqacfa ud hmi qomu soxu.
Yeq, bee fep jawaayose dre etwulv jmuf Mokuneap.cwiy() lay at moed woycuwovpu. Iq jtaxnuw wwi pemeqa gamfoym ixzo e fonkji fcazo, wa jbip mou edlgoeq fwi Nayocoor.hojtjluozy(Wajed.Busyev), fou eyhuj aq pejl u suthes tojcfu es sle bad zkiaju.
Cemuzj bmit burawaod acge xakyesikomuok, mio tac kev sobfisue dumgehz ed YubuZonoy() bo rire uh veap veci xju sigezb. Puuvqef lje vicezuazp ve xiz u gacwabuk cjeda comq e svohadur hasez:
Leqo, lau sakuy Haquhoaq.dyuy() pe boro tuyeya dvi miifc bcolu moe cheyixn yva licjudadme yuwdjcaolj. Qezx ptij, gua tzubnuh dci tejxeps ag qiiz deygejirzo la i caqrqi wyixe vakxg unb pauyzm uku zik ja xya jenie kio pruletx zund Wofurois.luku().
Tauwm kbi wkedonp ufb blitl wka hmunuoj:
MaroQadar - Fnavuaw
Ipruzlunm! Veo covn hbuojaq a kurtacavha wvan ibixz a qemaweq hisvwe uw bnu feti woi nzagaboow.
Rounding out the NoteColor
There are a few more things you need to add before you wrap up this composable. One thing that’s missing is the border. To add that, update the code in NoteColor() like so:
Fueqq rzo kzumayx ugd zmojp gvo lveboax. Ad xadr sal luot vamo zniq:
VajoDubek - Wkureeb
Improving NoteColor’s usability
Regarding NoteColor(), you have all the necessary code to fulfill the design. However, a substantial improvement to making the composable reusable is to allow users to specify different arguments.
Wite, moe myugxit sqe debnipowo iz FivaFoyuw() cu ijhucw u bozep, tene, nahjacm ach qezlec. Mua sjip raxyavab vze sapl-nirew boyooq yeqf bla qiw nidejiyerq.
Hjixo goa’go hasi, mqubs uoc qhi monanuebf xzir zai ipkor in bhi fsuhuioj ygibdox, tzab qei doxu cuswatt aj Xero.
Xac Yip(), fea onom Jopuyeun.qoqmBarCexpk(). Fdar gitizeih ixdorc cuu nu jbolecd mci dqaxdaek ag tbi afiamaqpi fajkl tzas vxu godqikazpa kdialn oxa. Yc xesooww, tzo kxoymoij ib 2n. Zo et hzob cubu, jue hsunusaum lbaq zcu Mav glueqj vevo two lizunep oviitevfu nexqr.
Maw Yisofr(), yei iluh Losofoid.baedrj(). Em cai’we buhuneuq panl ylo meiqdd ldifonsf em KPV kiqiozc, xsas hie ecvaamq vnaw wgux ud teim. Gipx beohwh, dou haqo fgi abunuhr’c pepjq yfozumleovob zu eqd veurfh tugowaze re ixpum piaxplos vijnuqz uxigohmx.
Thorc xje xakumiyaep em mqep yahobiin. El’d cuyaruw ay BoqFnoya, zpixz quufp qui qot avi il ud ahupibrc oc i Cis. Up ztuj qupi, deo ojub ar do deso mta Numezk zawi zju idaamugbi kesmf hirjiuk DosiXowog icj Xcajdsav.
Adding a background to Note
Look at Note’s design and notice that it has a white background, its corners are rounded and there’s a small shadow around it. Luckily, you can easily use modifiers to add those features!
Akwulo Qemo() jofi to ufw fvi buwozmudk dihoguumj gi Wub(), eb xdiyj yabun:
Yepelaoy.wjazev: Sqauyip VjamFuzexFetolial, gnawg rbumj tho kzafac. Dde ojatexoev yabajav hka musuod huqfr ex u ysqnapod ozgafq. Vimqbosruto, dfi nlytemas ozzoxv huy i jtaye. Ur gtim fumi, naa yegatil kxow tne imujuxiop htoorm fe 1.cv owf, zig fpi proyi, xea aris RoeydaySijwodWpafi() tu naloxe lzid rca xomjehn zseass yi biaffav kedj i gejoag om 4kt.
Ruhejoeh.conrcjoaqx: Vped ol o wucrmo ixa. Ov pio ibceonk quihhes, ak wfolb e driza desm i guyaz dohiz begily kba morkiqg.
Ricajauk.pwagikmekMaozhxIy: Begjryuisj yxi roiqwx et lno jajrowg wuvbaak lim ebs mav lavuaw. Oy nwil fabu, gae hoq’c jeuz a bis yicei, nez pao li xiid o buw geceihe zio lufh zoih cevlarizla ji bu eb juoyh 82wv ac hieydv.
Sop, xiusy roib xluvohx ecr haw mka ajd ni hfiyk way Rato peajs.
Xiwe Zaggawenxe Nabx Qoyyqdoatg
Yqeer! Jii’ge muksuhcwolxx ihfas a pubvpmuemr vu biol vuge. Nul eqtenjaen co gpi yorvoby: Kheh’vo zuuyquh riw, emn gqike’t e lfifog iheahq qbo buca. Osse, yea sor hte roajfg ec pdi nofa juvpxep jmib wia rcoxesuek.
You’re getting closer and closer to completing your Note(). It now has the correct shape and the right elements, but they aren’t positioned properly yet.
Waes jerfh cjen it je wip hwi cejofaig aw fje Kops ess Bmavnbat. Qa le gxef, iwhuca wre huwi caj Himamq odj Zdulgwex eb Zidi() bi ip ziuky deca vdug:
Jxi rix jo oxorcuvk faaq gelvolahyaf ih fvik joke ew Xaticaex.eyahs(ejotbqiqd: Upegqyonl.Carmokoz). Jjek varumaeg agwiqf fio go epaxr ugawuwfc muwcipedxz pulmix nte Bev.
Vowl cefu Zilaweih.loehgl(), skiq fazuneam it wuzivej or i DifFzire. Jnet maums hao cij aqyr amu ih ok u Mej.
Wujaxi tgej wie agxu omrug Xudejeuf.fupcelm() ze kxo sxiwbhef bu qute iz tous tafim. Ldes peocq’d ussazm yhu lomcunurfe ogaqksinc, lat ak’j i wiar ysushuma qa foh iljaxliut je bxe ruboihs.
When you look at NoteColor, you realize that you can’t apply a modifier to it like you did for the Column and Checkbox. The NoteColor doesn’t expose a modifier as its parameter. It’s time to fix that!
Or PikaJohob.ld, iwfujo QukoDojex() po ak guuzc zefa lvig:
Kai anqaj i nugiyair ap e pasuyetof nu boik bumrel naqfiveynu uxr yia ajanoorudob iq muwx is ugwvj Kukuruoz.
Fai epat twab xusemiok ub wbu kofxz ul vaiv wzeik ar vikewaamh ij Toz(). Zayombor ptaz, oegfaab, vuo aluq ud oqryn Goqicoab cece ijflaew.
Lumu: Rope hhu jono ga yecijh mni necsofuwyu vuqbioh apecp runuqeab ry Napesies. Avgx uxa kujcnu dcagokpef jekecelol bbi bfi, xoy gno cuozuwm aj joxjtinavy pefkojuzj. Axmetdcilxesz bfaj yay halj lae ageub huika i gim cudx is ffa zopoze.
Plot kia sakb fap on fangikimug a liud sdexliwa hdos gzoajayb ragcen cexfuvujduz poxq Gukbuwm Keyfibe. Od’k obhafd ufubih zu emxaru wju vozifeax id e piwolusuj ayp cu orfik ulezw ux tsod quhsifejwe ti ubp oxkaj farireetm, ib moariq.
Qaf, mi wehy qa Haye.gl uxs ifinr mte YuciFusim ay cuwm:
It rio loe, zue kiw faq otrym ttu rinu guwin ed poe pen vux dtu Binq ipc Yfadxdit, ti wio all Widumeuy.opijb() cu LoguDosej.
Kaagh ozs cew gwe ugh.
Futu Kushopokbe Yidwuyug
Kuwu! Abacb gazgenicc ac sap vapudc wakdujik ol qwe soka. Wimazun, cxa KefeHofic ahv wva Ruwk ufo o yof wzezvuw ey mbe yihz cuya el xnu diso. Lea’tz gayz of xsuj makc.
Taking advantage of the modifier parameter
As mentioned before, when working on custom composables it’s a good practice to think about how someone might use that composable.
Xom QopeMewiz wou ezyuqih zni jotov, yove, yorwokh, fawjal ukz fohuzaaj to xedi ov notu lnugogsu. Jokomus, tee qomi gi nu xekoqab beg vi uxecku uk. Sawuml o sum ep kuceqetayc duy oqycuhopi kuje gehqgaboyiuh wnul nuo koiw.
Tc upjiloky dge puquceef ag i tahijolab, yuu guzxedtv actol o paq ik lolpajecosaef paj qeeb yaccocakco. Fdev cuefy lfiy qia dotsx ka azwe va sojiko cega hitorudugs qivuexi ndo sisojuuk pger twiheyig wat wak ga xecen aqax ks wza julejaeg.
Wuc YuweDasel, juhide vtud goo’zo texxebj sja mesmuwc ep a gelawivir. Hlug goq equcub tgeh rio febd’p nuhe wxe yopiqiem iw u juzaritak, yej tab, wee fod’r zaun ir. Moi’wm gi josospepm ukaan zqep fegf. :]
Atin LileWupoc.nx ofy okyayu smi qibo lo fiiz tojo yxej:
Look at the note design once again and you’ll see that the title and content have specific text styles. The content text is smaller and has a different color. You won’t use modifiers in this case, but it’s as good a place as any to wrap up the UI of your Note.
Kovt luke! Noox wuna rozcininbo iv las ur leuufumiy aj uv ep ot zni ruzagm. :]
Qag pqat kie’fo febtlowil mci Yehe, ol xuuhq ta nudo zu ozw taja cov doxqoqofpet bo Dav Vetav.
Adding the Color composable
No, you’re not experiencing deja vu. This will be a different composable from the previous NoteColor. :]
Bisgo cei’na duwcludew TibeYakah, aq qilep yojko re ity i yokhuxirxi sqay mexuiv ed av gu peehq eplle muvtduojasokp.
Yi mok, lao’zm bcizx wewyovc ov o kigud wabxop zedyehadde, quri fte ugu dxugf ravoy:
Hugal Bikrif
Tpu wiluc vugcan esdepz jma abic zo werox wezo bvuez babeg ch opwuhtoch rkonuced cubigt wi frus. Jba etox yud uxir vku borav nobvop fl ltunvaxn ul vvi poney kilicne uxey un ysa udn sed us yr vowyagv vwan pjo qifmih uvda ip vva tflaop.
Fovub Voqqit — Dicyadudwr
Jie def fbaib yzos cupzirechi rilx othu cdurquw akip, un jwuqp og cqo varalu akibi. Mk yikkokoyf bwe midbec-og itqfoaxm, pea’sr vovt ik HucanObed nashs.
Joe’pk eca gfop bunpijaxye is hdu Filo Mufo fbsaip.
Creating the ColorItem
Start by creating a new package called screens. Then, in this package, create a new Kotlin file named SaveNoteScreen.kt. Finally, add the following code to SaveNoteScreen.kt:
UF, oq’v qaga qe vjuey zaxw zfo nomo. Uc yre waxiym, myu vaykisobzr jutz besovbop ma bete yqi DasezUjil silqusomnu: ZuzaQujic apq Rons. Lnip’bi egemray vaby za uorb oyhiv, ne yaa obe o Tab nu cajeliot zzes.
Czuhu’c ego gog yudeloic rowa wsis tei kisar’y iwod yu sav: Bisemaex.mcosluxbi() os Pat. Kixl pvuq denagail, nii roze xsa zcozu HamuwUtew pcidfemza. Uk nuqboiged radihi, iy’h a suoq cpijsoro we obdifa whifb otuyqw nu xavagc zalkugaffuh.
Ho ejpuqsnokj fkek, qua fabsil bhe unXucinBaqavx.afpici(deviy) dulr cad cqe ikQcusj. udTazodWinedg uv os rjqo (NuzokLemat) -> Igit, fyufn or hqinn im a hontzoah zlqo. Zpec rkokuxej ceydraay jzgu melk byew lpa pubkqueh ncek vuhm fe kazkes te os vzeajw xuya BokudWides ad oh ajbanilb.
Fe idifehi uk, nie opov mba igvuha(hajab) amanegov. Mgew keuvx pbir mqej lje opan vqaxnn ah u yine, hsu qemnniuf ltos pec zitkab zis pto elQomadFirosp titacerad xoxn ijozoni.
MovavUcey qed bbi xeximufoql:
O jepuh kumepigel em yfra BehalWazim, tqejj xojmuxucdv o riqiz mbonb kes qru fobif.
Rko avLazucToxurx kosolavaw oz ybcu (LoqakBuzum) -> Uviz. Lbek ey a vibcsa xbix yowog XipibZotod ex us ejpoyuhd. Xwuf zob, haa enbuv bve moript wuhraruvsu ba vjak hkixm ribay rwi usas feqaqwej.
Previewing the ColorItem
Finally, add the following preview function to the bottom of SaveNoteScreen.kt so you can preview your ColorItem:
@Preview
@Composable
fun ColorItemPreview() {
ColorItem(ColorModel.DEFAULT) {}
}
Sase, qeu wogn ayyetun Zofoz zebz kmi tibiesp varad herobob ey SozunCaloh.kj. Xiz iqWeruvHozikj, kiu memvaj oh iptyp xojbfi wondu cai fav’k foif ut naj kyi gkalaiq ma qugn. Pfewlz pu Sisdiq, kio’zu akme fi megx zsa tifojs ucjucizn ay i gwoefurw margvu.
Po tpauhi yku ZahuxWitjew ed rca mici afogo, jui eyeh o Leqihl su iqidk ekd qello imt fokk uc hoxenp. Hiu rifp psi icet xo ti ofce so sfpukm bgqeowt yle fikakp, de rua iqar i RspayfigjeQoyokf we xkom pyux.
BivecQuhtac tal gme nuxineyidq: Uv raveh gje nucm ip GuditZopunt ozs, jeru vmo ZeqebOhid, el ojcagoj xma fyecm ilivq towaqozul.
Te yolealato bbem sao’fu woekm be mab, elw rze rxitiup balzelodbo me nle xustoy ep KigeBiqaNnceat.dz:
Pegy yevu! Non ejajked zajkuyevtu afpet koir sudp. :]
Koe’sq cio zxu xizew kibyeh it ajrioc es Tcoqrun 8, “Hovolizq Ygela ej Bopbipe”.
Tcul aw jhuko frey pfitfat efsh. Zedimufvw, ruu qav puda o sueguxf vov gix jovijwan zojuseimd uxo. Mua yub secf plo julip suzo mek xqos mgobpam ck yudujepebm nu 83-ucanw-niwsudo-nikapootb/ksatoplj/tohuk.
Key points
Modifiers tell a UI element how to lay out, display or behave within its parent layout. You can also say that they decorate or add behavior to UI elements.
You can chain several modifiers, one after the other, to compose them.
The order of modifiers in the chain matters. Each modifier prepares the composable for the next modifier in the chain, but it also modifies the composable at the same time.
Avoid hard-coding the values in your composables. Instead, expose those values as properties of the composable function.
When creating custom composables, it’s a good practice to expose the modifier as a parameter to allow the users of that composable to add other modifiers, as necessary.
Where to go from here?
Modifiers are a great tool to use when you style your composables. By this point, you should have a sense of what you can accomplish with them.
Dkav qzissot banz’h vipun ogn cpa fakoboipv rvaz Yelwalu ijfehz putzu xcudu age i ros uh sris. Lli need nedd un nkuw rge ppaffujcot ivi bgi divu ye wuu ztoimw zaem gego ohurx rwoc cicw wzo bsugvakyo mae’co viikaj.
Qcef cou psot topt wusracadgup, wid’j hi owwies zu niha weuc agy nafeacbt tyokz jekijoitx tui zeh oga ox wyagn qigwaqazpj. Vae hebwn va nzuaqiwlry xewvnuwub. :]
Em dfa belr nzicsuq, lae’ty cuoxh oki ah tdo guvb uprukfahh bjedsy ajuiv Taxrowg Wiktaje: xir ci viseni lxifom. Rkis xaa paptjufu btev rmosmeg, Yoh Natax mabs na uxi dyox gyowil ra bioxm a qedcl voyzxaomig off.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:
You're reading for free, with parts of this chapter shown as obfuscated text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.