RoboBinding是一個實現了數據綁定 Presentation Model(MVVM) 模式的Android開源框架。從簡單的角度看,他移除了如addXXListener(),findViewById()這些不必要的代碼,連如BufferKnife那樣的InjectView都不需要,因爲你的代碼一般不需要依賴於這些界面組件信息。下面以一個最簡單的AndroidMVVM爲例。
Layout:
1
2
3
4
5
6
7
8
9
10
|
<LinearLayout
xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/tools" xmlns:bind= "http://robobinding.org/android" > <TextView bind:text= "{hello}"
/> ... <Button android:text= "Say
Hello" bind:onClick= "sayHello" /> </LinearLayout> |
Presentation Model:
1
2
3
4
5
6
7
8
9
10
|
public
class
PresentationModel extends
AbstractPresentationModel { private
String
name; public
String
getHello() { return
name + ":
hello Android MVVM(Presentation Model)!" ; } ... public
void
sayHello() { firePropertyChange( "hello" ); } } |
Activity將layout與對應的presentation model綁定在一起。
1
2
3
4
5
6
7
8
9
|
public
class
MainActivity extends
Activity { @Override protected
void
onCreate(Bundle savedInstanceState) { ... PresentationModel
presentationModel = new
PresentationModel(); View
rootView = Binders.inflateAndBindWithoutPreInitializingViews( this ,
R.layout.activity_main, presentationModel); setContentView(rootView); } } |
這樣layout的{hello}與PresentationModel.hello綁定,layout的sayHello與PresenationModel.sayHello方法綁定。我們不需要在Layout中定義TextView, Button的Id因爲我們不關心,且沒有必要。當我們進一步觀察時,我們發現PresentationModel是一個Pure POJO。這也是爲什麼軟件界的泰斗Martin Fowler在2004年,提出了Presenation Model(MVVM) 模式。它是我們所熟悉的MVC的升級,進一步的把界面狀態與邏輯解藕到Presentation Model中。我們可以通過以下幾個示例項目學習RoboBinding使用,他們都可以直接導入Android Studio無需額外配置:
1.AndroidMVVM,最小的RoboBinding使用例子。
2.Album Sample,是Martin Fowler的Presentation Model模式原始例子基於RoboBinding的Android翻譯版本。
3.Gallery,是用於展示RoboBinding的各種特性的使用包含Fragment, Menu, ViewPager等。
項目的中文文檔地址是:http://robobinding.github.io/RoboBinding/index.zh.html
github 地址https://github.com/RoboBinding/RoboBinding