【Android】 MVVM — Data Binding — Basic

自從2015 Google I/O 推出新的 data binding support library後,MVVM的架構也開始被廣泛討論使用。

使用MVVM架構前,可以參考以下的來源了解MVVM的基本概念

參考上面的來源後,可以發現MVVM主要分成三個部分
1. View -> display data
2. Model -> data source
3. ViewModel -> handle logic

因此接下來會介紹如何利用Android data binding建立以上三個部分,以及彼此是如何溝通的。
剛開始先介紹Android Data binding的基本用法。

首先在app module的build.gradle中加入data binding

android {   ````  dataBinding {
enabled = true
}
}

Data binding的layou與一般的layout有些不一樣,root tag必須是<layout>
而這邊建議model class的命名盡量以Model結尾,view model class盡量以viewModel結尾,且以data tag開頭,在裡面宣告。

建立Model

這邊只需要getter,為了在layout file中取值。當然也可以設置Setter。

Using in xml

在layout file中的@{model.userName}是以getUserName()method取得值,接著在textView的text attribute設定。
@{model.imageProfileRId}, @{model.age}的概念都是一樣。


接著如何在Activity中設定Model呢?

當我們在layout file中使用binding,android會自動產生ActivityUserProfileBinding(命名取決於layout file name),這個class負責處理所有在layout properties binding(e.g. model),接著在setContentView後,就可以開始使用此class進行binding。
最後只要使用activityUserProfileBinding.setModel(userProfileModel),就完成binding。

以往我們需要再Activity中setContentView,接著findViewById,宣告完UI Widget,最後再設值它
使用data binding後可以發現,activity中的code變得很簡潔清楚。

以上為基本data binding的用法。下篇文章會介紹viewModel

)

HsiangYu Chen(Shine)

Written by

Android Developer @ Travelstart

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade