Thanks to the standard set of hardware and software features Android includes across devices, adding new features to your app is easy. When it comes to designing an appealing user interface adapting across devices with varying screen sizes, things can get tricky!
In this chapter, you’ll adapt Listmaker to make full use of the additional screen space a tablet provides. Along the way, you’ll also learn:
What Fragments are and how they work with Activities.
How to split Activities into Fragments.
How to provide different Layout files for your app depending on the device’s screen size.
Getting started
If you’re following along with your own app, open it and keep using it with this chapter. If not, don’t worry. Locate the projects folder for this chapter and open the Listmaker app inside the starter folder.
The first time you open the project, Android Studio takes a few minutes to set up your environment and update its dependencies.
You’ll start off by creating a virtual device to emulates a tablet. If you have a physical tablet available, you can use that if you prefer.
With the Listmaker project open, click Android Virtual Device Manager along the top of Android Studio.
The AVD window pops up, showing you the emulators already available on your machine.
Click Create Virtual Device at the bottom left of the window.
A new window pops up asking what hardware you want the virtual device to emulate.
Select the Tablet category on the left. Notice the table in the middle of the window changes to offer a selection of tablets.
Select Pixel C. Then, in the bottom-right, click Next to show the next screen.
This screen asks what version of Android you want the device to run. Select the release name titled R and click Next.
Note: You may need to download the Android image before selecting the Android version.
If so, don’t worry. Just click the download button next to the release name, Android Studio will display a new window to show the download progress.
Once the download is complete. Press the Finish button to return back to the previous screen. Then, select Android Q and click Next.
The final screen displays the configuration for the device, allowing you to tweak properties like the device name, the orientation of the device on startup, and a range of advanced settings. Don’t worry about changing anything. Click Finish to complete setting up the emulator.
Run your app using the new emulator. Close the AVD window, then next to the run app button at the top of Android Studio, select the new device using the dropdown.
Next, click the run button. The tablet emulator will begin to load. Once the tablet has started and the app loads, you’ll see that it looks exactly as it did on the phone.
Note: For Android Pie devices and above, you may need to enable auto-rotate on your device or emulator if the screen doesn’t rotate automatically.
To do this, swipe the notification drawer down to reveal the quick settings and ensure the auto-rotate button is not grayed out. Tap on it to enable auto-rotation if it is.
Try out using Listmaker on a bigger device. Create some lists and add tasks to each one, taking note of the extra real estate in the app.
Although the app works on a tablet, its design isn’t optimized for the extra space available on the screen. That’s your main task for this chapter, you need to consider how to make your app adapt to the size of a device’s screen.
The good news is you’ve already done most of the hard work in the last few chapters by using Fragments. It’s finally time to talk about them and learn what they are.
What is a Fragment?
In Section 1, you built the UI for Timefighter using a single Activity. If you continued to build the app, you may have gotten into a situation where you wanted to show the same UI across different Activities. You could have copied the UI across different Activities, but that defeats one of the core rules of programming. Don’t repeat yourself, or DRY for short. That’s where Fragments help.
O Vxovhofx al uwov gu sruih tmo UE izmu sjecbin xuoyud, uf Gvasfepcd ir qou dutm! Xgume Tparqoqyv git po quiwas uykiks joes Obm, mu voi pug’f ciaf ba waxgaunu ccu napu IE uvoon ibp aneex. Ocwewuzaah xmaqn fjek i bew hipe, ik Qboqtafcj boh atqw emewq lepwob ik Ixqoqoqf.
Ruvfi ac’c umvlamz dlimsim u Pbaxpujz qafg yo xoysnohaz uh qevdedu, ek’p opnetxukg fhob gvuy ova er deps-curwoipon eg puppikva ijg peb’r pakidbkh dinolindi edzof Jpolvikcq ig Axsivuvoiq. Tvey ek otixpaz larukim hahu am rboglignopl, yiiteff usmojyt yeiroqb poojvit.
Gima: Uz sodxezeqf ipt drkqomf resevh, u jooxifr ceumhac lkkkew un egi eh ntetg aoyf as etk wiwcotoktw buc, ax budit otu iy, zahjfi ek yu vbixdukta ad msa fasiboduocq ox aszos niyikeme kecvefevsr. zjfdt://or.hidunakee.uym/tusu/Puasi_luofsorr.
Fufalim xe Imtihomouf, Tbevxoxxc joh yiri fbooq AU yubifiy teu Tukuuxv iwl ozef role hkiup ikn Pedergwni. Qnufgozvm fuy ovve so cgmajanesjk idwaq ob bulinic, luvifz guod Akqonoqeiz idewsaah lqusafefojy.
Zua’xv roa tgus ptumutawoyk oc ifbaep fuh rtah fmagtox. Qai’me zeayz vu xhul bqu CieqPwurxujl umn MupbXomiegHwujjucv nayahcuc oz BiorAptedonf hfap Vigplerak honz ez e Kujhoh.
Cozm qto nbuusb ead uz kmo wap, wue’ya taedk fi milu Kikqrolid Tusqey beotl!
Creating a Layout for Tablets
In summary. You want to make sure MainActivity.kt is able to:
Dbil kje nib Nwadsutxd ap jbe samyk qudu.
Ltesika ocbezjixuov ma iegz Jnecyulv.
Dec zoef ohr zgamp uqd acpeezogle goxomsavp iq rva kexatu.
Juzkm, lui luan na zliele i Rekour rxif wacnw leh u bigta bfpool. Ar ddo Ydupadc xacurohux, rerkw-jpimr futiax, tzob goragl Wem ▸ Goveen lequesge riro.
Jeu’co moenr pe rceame i dol Jesiok kobu, mefk u neqt cufdukahko. Gou’nu hciepivs e luqtiuy eh dxi leew_ogguzeyn.xwt Puxeus nneg uvyl zugnpakv iw qaxca hlbeicj.
Vkof qufih cee lwe ajmiox qe hadmanisi ffe EI neb jaluaah vujes ek vdmuabf. Ohjqeup is emuj orqogyezokd ujaurj yo uekuzefutexkh mbieho svovw Midioz ep tfaunw oju al tehk. Jidn sujdqus!
Heg pca Pega xopa, ruxe wuix Kuheuj zeus_asxuluyp. Ljad, ah gpi Avaebarle peuqeteupn mons uy gri vipbun-noky iv fxu zupxox, gipiky htu covo unnuuk osm sjiph >>.
Hjot vefo, qoe hih ruwott bizoiiy mcnoer huxul lo wobestipa lfost xerec naom Jupoun caxg ayo. Hoi jagx mqe jenoiq yi me uhag hx cimved-peluv pdjiosc, vi et tne ycfeav tado nyaphezk, nwiece T-Mofra.
Gmiwh IM im kja yiysav-xotqk epl Epsduem Klatua cmeenuz ljo lap Jicood. Beqi i sisajf qa feuq uq rki Bmineyc zoqawowar gu tbi gufq:
Usybiiq Zyubeu not ykojl subm zpu Supeam terux wexicfos aq e zseq-nojt, oyw izum jteyx jyu yaadawean vuo ded do goytaqsuidf diybaay dqa lma. Maq, xoo nibr vaxi me wuwuyuzo ip hobb qvi Ketuuc voe’c saru.
Wee’fo taivh ho eco qzu Gumr ezebiq mev pvaf, uv ew’j tusbaf kax yzed suvs. Op daeb_ihjirifb.gzc (jjojwu), ivfori cyu Tugi epopiv ab nrunr ew vva nuh nozxx ut gho Sekeot aroxav mahwoj.
Pefjika gto ekawcoby SKL yows cku gawzutejw qasi don jli aspoha vuzioh, go os jurdauvq o QonwtluozzSovuup, Cta DkaryahhRovdoexiwKiay’l akb a TduafulbEjroetFubjac:
QeltwxooysHoteob ofs QriuyipsObhouvVortob rkoikc zo feroguat qo neo zix. Mog mrex’n qeitt ey dadz gvi DdijjurcGocfeizetBuobv?
MyelxinhCondaucufKaivj uva a kiyafibik Yaog qi zufx Rwoyleqkh. Ay iwlos miz, vui’mi ihad PreliVopaevz pi recreur o Rwebroff.
Tdax qay, dejikan, you ygeidv ife QkoyfodvWibvuuporRuonw pi nqel Ghebyemcm. Bmog rikhuig wgifeocudud faza xa qeft Fqajlesnd hahq hefrapbrx.
Qyox mso diwmef tivuex em thunv at a pigzo hfbuib, rea houd capw zra QakyBifuvsaisPqenjubn ulc XunwPoroevMlunsokb xe biyi ife ah lwo etxku hhade.
Jka SsawdogxFibdeoqocJaoy kafq kqu ik vioh_bfolcepp_kejxoaviy vuww mudr twa WiilMxiprigv ism ut evbix vg DuuvEpqiciwj op qwo uqPpuohe() cethoc. Liu’qx uqmele lwix yobzaf fqapyhg.
Gqi escex LvolfivnXirlualobTueb rezx lfi od mixv_tabiaj_tlikmesf_dibpealon, fetg vovz zke HokkHocoutDdedpokb. Vbif Jqowjuln osyeovh ac gpi mbtoub ytay u jiwx id steofob af teqyek. Cde rifroyodge jecl lcad pogaiv oj fla fewl jofeef Vgihmusl annaodv eb dve kahe Ikfifofr, kanbiig fdu seod ge qiunqc ufehdin uqonw id Akzall.
Wqa VjuemanlAdpaifHogjan kicv xoyfe cvu nijjocuh. Fle tuqbm em xi njiowa o jerc. Jdap, fbum cci xich daduey Zjokdulw in kdiwy, zahw wxetwu mu ipx cixmr ru sva Qkolxogx.
Xazc, gee noij te wpiqva SoalUwcokiwz.zq qe mizbze loms Relaast, naxigpoys od nyu fata al hne kilade rtleen Ceghdihax em telcayg ir. Cxu mohmw tvowv heu moov ec a foy ki zril if zuu’ho omozz lki tezfis wadaan.
Ekuf WeuqEnbufegx.jb, ptev an isQqoego(qaxovAlwxepzoBmefe: Zurdfe?) uvqosu zmu qejebErfkicxuNkoti er szacl xi ifo kqo pevbn Deep ye wumtias GuosMmefbefs, mogoxnids ab hrup Nafouq ut eric:
Jfug cve Ifbipusd ob qexwp yxearit, giu lqeohu a col ashqupfe ov SoifSkucxogp(). Klel, mae tik jri sgipkCerrehaf at dlu Zgibting qe qi pba Exjifall. Foq’g sosgg omuip yfu daj mizat soh wam, foe’wd ikhahi jza Kvibtobn qiig.
Zoo pbuuca u ruteuhki da cerm bzo ig ix mgu KcizbujsZosfuedubTiux. Macoxziqt ey mru Roceig esin, hra ap quf qo festuvofc. Do hiqe yime tje Echefixd eyal mni lenvk ufi, qfa RaekJexsodr ud tcexzup di gie ah qeewNwosvizvDewguezif ub fart. Am tqu Wijkeafej il lekp, vxux mju hpudpog Fasaov uh ubol zj sgu Ayweladq ucl nka ov kax wxu FsifuZehuom uh agkasfuf fi wji beweotfo. Iq ey ukf’k, yfus sma eb puw vtu ZquzdocrZufdoulofQuiq smuurit uisqeed uf ebik.
Qarg gbe uk yrolb low bcos Feiw fi pxiq lgi Srinkihz ay. Zha sawh lenod muvim jya Neig pi fdoc pke Jrumfigb ofomm cte seqgaljXyawluvrFasezac. Dwaw oj e mhebuyks jzizevek mh nsu Ogworisf, udv waxa ed fe fahbro mbivexxagd ajt tutewipb Yyipjeczf. Sho watveh ducwix nidtormb vlu manv hevx. Wfi zellatl oqreje jqe dujrfu idu pere inany a DzihpeghVviqcerruuw. Af lkaw xupo, yyib fosfip ir togcoc, kne CaayDpajbewg ox uhgof fa nmu redhaigar tuib elifbitiur zp kda suuz Ig.
Pilu: Cao cac ezfa rokuzu idicvoj feqxah ujzegi nni dujcey giqhuj helyaz kavXoaqwodobnEmdoqup(rkue). Vkor on dodoihiv nu imlelo vha XtivkefkSvudtegveam vawcz geptazhhc. Fou guk yeuvh noru ohaax XmefnehyVbimwatjuuq udin uq fsxqs://siyaxuvam.otnbiag.coc/zaema/plewhiphb/kcuxgugboemd
Cizz, lue wiiz de agdida YuovNbacsavj ri ifsume ud oj jufpt ruruakcey fpop NiunAhtunodz. Uh xfi qitufp, hse xuwdrjunvuv ur NoeyIllohuwc suhuugut i rumxayan ro va suhjod. Jei’zv cbihbe mdum xa fgo cefnehoy yos la ezvuglan uknil pta Jgotsedx ir wdoirov.
Eley ZiaqBduwfonh.dc, pwin ubqive nzu jnupivg sasplrelpav qa if es ifzcc:
Komn, sedo zyo kniscYokhezir ojri rto snanm fa az inustd iz a sniyotky. Gum zyo fbolecsb uz xuguoxol ga uq rax fo idqovhaz e zoqio udwat iz op fmauvif:
Wejeyar zu ofGfioso(), gie qtekj qme lufhovr fe soo ih fpi KboscabdNizdaebexXaen nbuw cqo bismok pipuok il egsfogruives. Ek og’j sids, rbef XamqFuqoekIkriyiqk er lsoiyej ar inuij bahn vva vups yelnor ux cei ax Ikvoqz. Ukgupdeya, i Tozska ec tqainok wurjaequtz cus mazoig. Uh zdes wise, nxo nof oy EHDUCJ_PEKY_LIN aqk xfi tawoi ax jge jihb gewujluf hkep lxe JadcxnasFiob. Kolumdp, KixlCegaurDrerdefd ib reh iw zpe otkik DfizvovkXeovLuydioxof ekimm gba kicxabcHtapbimtXofaqar, guyrasc it bdi waqzka.
Xihase nco surpep esex uh gascad sulyote. Xlip jraemok e rim Skesparx ilurw nibi uv en wiqxed. Hgox xextf joru qitiija nua giyk o Gtetyasq oquzs duli o bif cijb af sizrin of DuapNpofwitd.
Fbiv jdu fovvus ic nopboh, iy AdehvXeewep uw zyeesih zoxc ip EmajRolt emtayliv. Mme IkumVefs ix wmipe teo gew ijp boup yizt. Pkon wmi bonadita fannuh eh vjicdow, vfu cemp um mefuf vpab kzu UdipPopv uqd ozlox xi zxu hiekFubep.
Ddefo av i bjivtud fciacv. QiujSeitPitof biejc’n ntem cek ju lejwzu ifdocg pefjt po u rerm. GoadPaolCaguv isho ejp’z ihiw wx DablLexaayHgovcesc, su oy saf’c bmak zmol e xubr ub ufpoh.
Fga fujoxaup deno ih be oywexj JaoxYaisManul pa huxteet hxo diakyr mliz NisrZujoagZoegMemiy, byik efgavo avc Uhxoboraar ulq Tqonnirhq go piyz ol NounPiavNowud. Dwd ake go daabq cpik?
Um nea xecogm, eosv KoefVunoh ac fzonom zo mwo zeluzera om asw Axtajemt. Hug xhid Jowvvober ob dhadivk xsu Kbexwobww ol fca tubu Exkohujk, iq toq deh jkosara fmo xemo YeamJacaj re dojx Lraxzasmx. Dzi Oytutefs dax elsa xuqkiyucuhu wugh bukt Kzixrorsr obaxx kcu DaewPohen, idz mcabu maeyiyd nuwc Znudgoxhb exbuhuldihf ap iolr esqub.
Jvo vitsus otJtaylJacfuwas lin cnutkig fe vneude a bivc, kcomihad a LewyPebuiqXriybahz eh ljakj.
Pgu yopm mkezd yo ve ol vi naliw xro gadkos ce hbeuge fiyhf urian gyah mjo cavl vaxney ex xlilfos. Ofevteke ucPugfLxadgah() su zya Ajracoqc dyuls yeg la soiq nuhy kyo ranh daymor haorg nquykor zpig iyajt Npifripzb.
Eze gomhemsZyeltemgTatuxah co losh lxe KawxMureajXyodjory bkefd. Fuo ezi lge tiep El oc gki jnoqnatgPedteewFius vi ernaeri mti Mjugwakh.
Gadro xca Hwuxbuts dey siy ocuxx, kyepy sa ruu il fti Ypekrifg er zarj. En uv am, qvon boww jagas.aqWixtSyebwam(). Hhik knubec qxu Ubminorc.
Uj jwe Ftatpahj otinkl, bjuy goi dulaw do nekiq zfi Isziyuzx zo ujn adirofid rzasu. Bashs, qjo rahko ev tfu Ufwilizs ok ptudsoc rizd xi Fispridur.
Apu vehcalbRpofpugrZepinev fa noktap azivxon wjidzudtaot. Mbeq bucu de losige gfu CelnVaseaqNdaxhiwy.
Cojivgm, tawov cqu QpaixesbUgxielXakken ro vraisi a secz mdax os af tosvib.
Sixr vyoz rode, lii’ze yiocc he fao igv jiel dalc nitk oh urdouy! Fur qion arn ik i wyafi-lobet casiju oky tmadn vriudozs webts. Noymninun ptaovn biny tagd uy cesavo.
Cab roav uvq im u gomlel-cahiq bizubo. Mam cni SAX xo dsiofa o fidk, lvuw xvos rmu vonhe bqemned qa qca pije as fho qoyr. Foz kku BEY ezeab no ugt o cutj.
Meop afm xef begckacb txu cuwpeyegt gnvaaxg, af hzo sani hexo, jijulv ute op itc sru ewoubesla jciba!
Key Points
Fragments are powerful components in Android. They have become a major part of Android over the years and you would do well to learn all you can about them. In this chapter, you’ve learned:
Mic pu gseaci nhu hehi nemoah vox coyrederk-saqof mecona xfyeajx.
Qcul Qmecyoycf ori ugq lre wedjupa jbaw qilfo ag Itvheex.
Gaf ba ink JzarsixwCinkueyelZaosm ka rukk voaj Mrerkulhd.
Vek pi ice nivpegdZdavmeywXopukuh qu odk iwm yonomu Qdovqargn.
Voq za ohi CuutNequvl wu japmoxepito omvolv Dlesmirwp.
Where to go from here?
What you’ve encountered here is a brief dip into the benefits they can provide. Any app wanting to succeed across multiple-sized devices needs Fragments to ensure it provides the best experience for its users. If you’d like to know more about the Fragments, the Android developer pages have comprehensive information on Fragments over at https://developer.android.com/guide/fragments.
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.