Android數據綁定框架:RoboBinding

jopen 10年前發布 | 60K 次閱讀 Android開發 移動開發 RoboBinding

RoboBinding是一個實現了數據綁定 Presentation Model(MVVM) 模式的Android開源框架。從簡單的角度看,他移除了如addXXListener(),findViewById()這些不必要的代碼,連如BufferKnife那樣的InjectView都不需要,因為你的代碼一般不需要依賴于這些界面組件信息。下面以一個最簡單的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與對應的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因為我們不關心,且沒有必要。當我們進一步觀察時,我們發現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

項目主頁:http://www.baiduhome.net/lib/view/home/1410667351476

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!