RoboBindingAndroid 數(shù)據(jù)綁定框架
RoboBinding是一個(gè)實(shí)現(xiàn)了數(shù)據(jù)綁定 Presentation Model(MVVM) 模式的Android開(kāi)源框架。從簡(jiǎn)單的角度看,他移除了如addXXListener(),findViewById()這些不必要的代碼,連如BufferKnife那樣的InjectView都不需要,因?yàn)槟愕拇a一般不需要依賴于這些界面組件信息。下面以一個(gè)最簡(jiǎn)單的AndroidMVVM為例。
Layout:
<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:
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與對(duì)應(yīng)的presentation model綁定在一起。
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因?yàn)槲覀儾魂P(guān)心,且沒(méi)有必要。當(dāng)我們進(jìn)一步觀察時(shí),我們發(fā)現(xiàn)PresentationModel是一個(gè)Pure POJO。這也是為什么軟件界的泰斗Martin Fowler在2004年,提出了Presenation Model(MVVM) 模式。它是我們所熟悉的MVC的升級(jí),進(jìn)一步的把界面狀態(tài)與邏輯解藕到Presentation Model中。我們可以通過(guò)以下幾個(gè)示例項(xiàng)目學(xué)習(xí)RoboBinding使用,他們都可以直接導(dǎo)入Android Studio無(wú)需額外配置:
1.AndroidMVVM,最小的RoboBinding使用例子。
2.Album Sample,是Martin Fowler的Presentation Model模式原始例子基于RoboBinding的Android翻譯版本。
3.Gallery,是用于展示RoboBinding的各種特性的使用包含F(xiàn)ragment, Menu, ViewPager等。
項(xiàng)目的中文文檔地址是:http://robobinding.github.io/RoboBinding/index.zh.html
