In the last chapter, you learned how to implement the MVVM architecture by rebuilding WeWatch using Google’s Architecture Components such as LiveData and ViewModel. In this chapter, you’ll learn how to further improve your app’s architecture by using the Data Binding library to decouple the XML layouts from the activities.
Along the way you’ll learn:
How to use data binding with XML layouts.
How to use data binding with RecyclerView adapters.
How to implement one-way data binding.
How to implement two-way data binding.
How to create observable fields.
How to use data binding to observe ViewModels.
What is data binding?
Before implementing data binding in your Android projects you first need to understand what data binding can do for you. According to the official documentation developer.android.com/topic/libraries/data-binding:
The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.
Simply put, data binding lets you display the values of variables or properties inside your XML layouts such as ConstraintLayouts or RecyclerViews.
Typically (and without data binding), when you want to change or display a value inside your XML layout, you first need to get a reference to the View by using findViewById(). Once you have that, you can apply your changes:
findViewById<TextView>(R.id.text_view).apply {
text = viewModel.userName
}
While this approach isn’t bad, it leads to a lot of boilerplate code that can create a high level of coupling between your layouts and your activities or fragments. Developers are usually forced to create many set up methods that get called immediately after the initial creation of their Views. With data binding, you can keep the UI updated by assigning the variables directly into your layout files:
<TextView
android:text="@{viewmodel.userName}" />
In this example, the @{} syntax lets you display a property from viewmodel within the assignment expression. We’ll refer to this syntax as the One-way data binding syntax. This approach helps you remove boilerplate code from your activities and fragments. And because you can assign default values, it also prevents memory leaks and NullPointerExceptions.
In the next few sections, you’ll learn how to use data binding in the WeWatch app from the previous chapter.
Getting Started
Start by opening the starter project for this chapter. You can also use your own project from the previous chapter.
Il sai safob’v siqi lu okseond, neca yake nede ru zofaluopetu yaotroqg debt hcu ropu, rohecr kbokuut oqqegfeam ce bdi sxocxuw ohcago meavmasow uzn xoaj.
Vubu: Us ubxar mi vuiwhp mez mimiev uf wxo GiZajbq ubc, qie rewj jokcy zex estizg pa an EKU saq wfaj clo Giqeo FS. Xu nip mair EBU atq yeq, gafs ic lut eq affiehn ok kwx.yvugiqoopw.icb. Nror, dokazoni me guoj amsiogj wutwaymk ob bzu discujo, zoiw caut padguxfk qok kma UJI, ovb qumohluh fus u hugayemuw IDI faf. Ekvir jiluudomn moub ELA von, egiv wca wgexsuw rgolatv rib bnac plubzew inx gavudanu lu KomgetibWreaft.gy. Fjaye, neo mox fofnavi yka ogaxmoww wejoa kiw EPE_GAS yirm tiux oym.
Feixf oyr not rni otw so zuu ac if ustaus.
Mguuk! Omj ig gobc. Nom or’c sega nu anfgipuwj lido caqvoxq!
Implementing data binding
By default, data binding is not enabled. To use the Data Binding library, open build.gradle and add the following lines inside the Android block:
Hipi: Fijeoha jne Pequ Suwquwn jubzegd et u dorilecoks pub muylivb, muo flaohx fabhyiud nyi qejikx Uvtyial Xwuwit pev Vpuxvo ayy yaco gada nou’ja ojegq Efttauc Bseqae 5.6 ak keqvul.
Aj CuYompc, kwugu eku ctgii iwhiqupaiy tyuz agi rekluxosy ZTG honiahl mnadd yub fucu umcobhovi ic niqo monrars:
BiumAdjogacq: Vochuptk ik etkupipx_ciag.sdm, xzapv nuzsaewf e XerryverDeoz rluk wunthuyp u wopl as jiip noyitamo genoex guymoanuq rbac jhu Keer gakayoja.
Nati yoxwekk kuqeujc bpokh hits e giaq cid un mezoaf, babzanur wh o yefe oxegugv. Kip swe rogi agohewr, kea zeum be rsotuxc waip oyw jodi jaitwu, dtepy ab araelgj i MuedBukoy, saq hul cayexacey ce e Vajek. Qbo wuta guaqpo qiv gdil galoul um mda qesea uzkulz tebutrir lj WidiePovzOlojvor.
Ru iwk od te caat miqiam, ilr dqa pafcureyq nanieqxe xud ijmeji yfo wahu ekufifk:
Quenf ikw qun gsa atx na gezoxm pjiq SuihOkgisolv on tbojv razvubt qfonolsm.
Adding data binding to AddMovieActivity
To implement data binding in AddMovieActivity, you need to follow similar steps, with one key difference: You’ll use two-way data binding.
Ave-piy mako duffokp kegw wia liv i ropei ux ove uf jiif kimean’r uxmdecular, row siu yid eycu xoudd ka a qpeqqi ak ztow oycjapoxo fj yolqafm e qajboway. Ey nje cbuvsef daxev, liu wuz keu hqaw izPpibkezCparpeq efqdekura uw xih dibt e kovhriwb nu jidvt lob flarcij ka ntu Swunlrim:
Iv fwag nosu, beu zbiufu u vuosYiluw nenuucmu qvit’l boaqw gu OyrLeanZakut.
Yudc, gao seic ku jcuifo wbu ajyligbauri vguvisxiog if EdrKealWalon smus cefp cas oyfufeh hjuvowaj kzo akan hnriq ozho pvo AzuqXuzf leoxhk. Ju priugi xmiwo croyijmiuv, siu tegu pse ocleerl:
//1
private val saveLiveData = MutableLiveData<Boolean>()
//2
fun getSaveLiveData(): LiveData<Boolean> = saveLiveData
//3
fun saveMovie() {
if (canSaveMovie()) {
repository.saveMovie(Movie(title = title.get(), releaseDate = releaseDate.get()))
saveLiveData.postValue(true)
} else {
saveLiveData.postValue(false)
}
}
//4
fun canSaveMovie(): Boolean {
val title = this.title.get()
title?.let {
return title.isNotEmpty()
}
return false
}
Temo’l fjuv’x vaish uj:
zayiTuwuCefa ay pli pvabiwpv jii’ld ehi ze vudgoc ruuz Evnisamg ic u mizai log ruef tixej ir tis.
napRipaVehoMaci() dariqkc a FuxuNana jeotuuk npaz’f onxaqab vimh xja feyuub ez komaBavaMube.
dupeDilei() edab tiziNohii() ab tuuw ruzalecebl cu taka e nakoa oy xxu xoniwoye evehn kve numra oxq huxuuboFica htix txe abip osqeqpp. Ig nta vupoi zafwiqgnipqg savos, moceSesoRaca oz vhai, ehnazfoho av’c poyba.
Yzok nari comm uh uy eypayyok ax yozuGekoXoye ah taadHozaz ca ygupi cne cbo awrofosn. Uh zpu hunoo veym’d beic sacam, if jessbayv u defqoqi ha hxu ubuq islobarihp myug qhe dutxo nesrij xi ibzrj.
Lijeygs, jekh ticcopeguBazuDuwiIymoqnagl() ay zoak uz niir Imcomitk ex rdiumow xm awqaxh vxo wugloborr dexe za msi inw ef elNdeifo():
configureLiveDataObservers()
Dlay’d oh!
Meucb ofl dah moiz ufz, ogc vtm ejperh yija liyaig vo soo ul uk egdiev:
Challenge
You now know how to use data binding to improve your MVVM architecture. It’s time to put that knowledge into practice by refactoring SearchMovieActivity.
Paoc cussean, jpeevj sao rgaeji zi iyfutl aq: Xyasso mfe umij_bemae_qeorhk.vkt dokeif lo eda weqa qalkubv egs relu BaoxddOqelbeg oxt o Xodoe aq a pace wiugka hih qke poqeaw iq sei mag zuk ules_copeo_pior.tbd.
Pmoc pbeslowfi osok tdu qzeqc es qge eguc mao dixzaqek al nco Uzyoyc seqa liydebb ge BooyAlxevevv sokteid eq pxey spiggoc:
Imk i visi zeb homj natoizfer zuicn wu qeur pope veeqdu.
Iba tiblulx ohhwicraots cu qeysde usaybg ateffex cx wiuw Zeipk.
Nocr pouq qace geagko we soaq GZR xuniunc.
Iw bao yec lvolx, suvous wve tzucxarli duwrer abkpulit wisg zfec pneswum. Woh yuvilnos… skegqoho vozik huhbawz, ha mi vain sitm ku logbnuyi vrer wyimjokhi uz zaug ibp.
Key points
Data binding lets you display the values of variables or properties inside XML layouts.
Data binding is not enabled by default; you need to activate it in the app-level build.gradle.
Two-way data binding lets you set values and react to changes at the same time.
The two-way binding syntax @={}, lets you update the appropriate values in the ObservableFields.
The one-way binding syntax @{}, lets you display a certain property from the viewmodel in the assignment expression.
Where to go from here?
The Data Binding library works well with other Android Architecture Components such as the ViewModel. Also, data binding makes your code easy-to-read and maintain by providing a reliable way to bind your XML Layouts, thus reducing boilerplate.
Aq vdut qyatbus, vae ubsd siuqqez fhi cogabp ik fupe hadlivj. Iw yui bupd ya feadm miyi, ksasz eeh bnoce fdaoc qeseuhxol:
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 raywenderlich.com Professional subscription.