Android端MVVM從入門到實戰(第三篇) - DataBinding數據綁定

前言

上一章內容中的代碼,如果我們延遲以后重新給實體類賦值,會發現UI并沒更新,在更早的內容中我們講到過,需要用LiveData去通知觀察者更新,不過這里我們要講一下另外一個方法,也是更基本的方法 - DataBinding的Observable接口。

參考代碼地址:https://github.com/guoergongzi/GMVVMDemo/tree/main

參考代碼Module:gdatabindingdemo2

1、數據綁定

為了測試這個接口,我們首先創建一個類AutoUpdateBean

/**
 *測試單向綁定的實體類
*/
public class AutoUpdateBean extends BaseObservable {

    // public修飾的成員變量可以直接在成員變量上添加@Bindable注解
    @Bindable
    public String name;

    private String id;

    // private修飾的成員變量要在get方法上添加@Bindable注解
    private float price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        notifyPropertyChanged(BR.name);
    }

    @Bindable
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
        notifyChange();
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }
}

我們讓這個類繼承了BaseObservable類,這個類是Observable接口的實現類。我們在name和id兩個參數上添加了@Bindable注解,不過public修飾的name是添加在成員變量上的,private修飾的id是添加在get方法上的。并且我們分別在setName和setId方法中添加了不同的notify方法。

接下來我們在xml文件中添加三個TextView顯示這三個變量,并添加兩個按鈕用來更新數據。

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_main_auto_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{autoUpdateBean.name,default = autoName}" />

    <TextView
        android:id="@+id/tv_main_auto_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{autoUpdateBean.id,default = autoId}" />

    <TextView
        android:id="@+id/tv_main_auto_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{String.valueOf(autoUpdateBean.price),default = autoPrice}" />

    <Button
        android:id="@+id/btn_main_auto_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="改變Name和Price" />

    <Button
        android:id="@+id/btn_main_auto_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="改變Id和Price" />
</LinearLayout>

再在MainActivity中添加按鈕點擊事件:

AutoUpdateBean autoUpdateBean = new AutoUpdateBean();
autoUpdateBean.setName("name:");
autoUpdateBean.setId("id:");
autoUpdateBean.setPrice(121);
binding.setVariable(BR.autoUpdateBean, autoUpdateBean);
binding.btnMainAutoName.setOnClickListener(v -> {
    autoUpdateBean.setName("name:" + new Random().nextInt(100));
    autoUpdateBean.setPrice(new Random().nextInt(100));
});
binding.btnMainAutoId.setOnClickListener(v -> {
    autoUpdateBean.setId("id:" + new Random().nextInt(100));
    autoUpdateBean.setPrice(new Random().nextInt(100));
});

代碼寫好后我們運行一下,會發現,點擊改變Name和Price按鈕時,name屬性和price屬性都更新了,但是界面上只有name變化了,而點擊改變Id和Price按鈕時界面上id和price的顯示都刷新了,這就是notifyPropertyChanged和notifyChange這兩個方法的區別,notifyChange調用時會更新這個實體類所有屬性的顯示,notifyPropertyChanged只有更新參數對應的那個變量。

2、數據綁定的另一種實現方式

除了繼承BaseObservable以外,還有一種方式也能實現數據綁定,就是使用ObservableField來封裝我們的數據。首先我們先再編寫一個實體類如下:

public class AutoUpdateBean2 {

    public final ObservableField<String> name;

    private final ObservableField<String> id;

    private final ObservableField<Float> price;

    public AutoUpdateBean2() {
        name = new ObservableField<>();
        id = new ObservableField<>();
        price = new ObservableField<>();
    }

    public ObservableField<String> getName() {
        return name;
    }

    public void setName(String name) {
        this.name.set(name);
    }

    public ObservableField<String> getId() {
        return id;
    }

    public void setId(String id) {
        this.id.set(id);
    }

    public ObservableField<Float> getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price.set(price);
    }
}

然后仿照之前的做法編寫控件和邏輯來測試這個新實體類:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_main_auto_name_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{autoUpdateBean2.name,default = autoName}" />

    <TextView
        android:id="@+id/tv_main_auto_id_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{autoUpdateBean2.id,default = autoId}" />

    <TextView
        android:id="@+id/tv_main_auto_price_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{String.valueOf(autoUpdateBean2.price),default = autoPrice}" />

    <Button
        android:id="@+id/btn_main_auto_name_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/string_main_auto_name" />

    <Button
        android:id="@+id/btn_main_auto_id_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/string_main_auto_id" />
</LinearLayout>

// 測試另一種數據綁定
AutoUpdateBean2 autoUpdateBean2 = new AutoUpdateBean2();
autoUpdateBean2.setName("name:");
autoUpdateBean2.setId("id:");
autoUpdateBean2.setPrice(121);
binding.setVariable(BR.autoUpdateBean2, autoUpdateBean2);
binding.btnMainAutoName2.setOnClickListener(v -> {
    autoUpdateBean2.setName("name:" + new Random().nextInt(100));
    autoUpdateBean2.setPrice(new Random().nextInt(100));
});
binding.btnMainAutoId2.setOnClickListener(v -> {
    autoUpdateBean2.setId("id:" + new Random().nextInt(100));
    autoUpdateBean2.setPrice(new Random().nextInt(100));
});

測試發現我們點擊按鈕時布局也會改變,說明這個方式也可以實現數據綁定。

3、集合數據綁定

DataBinding提供了用于代替原生List和Map的ObservableList和ObservableMap,可以用來做集合數據的綁定。我們下面用ObservableMap來熟悉一下這個部分,首先在xml中添加一個布局顯示內容:

<variable
     name="map"
     type="androidx.databinding.ObservableMap&lt;String,String&gt;" />

<variable
     name="key"
     type="String" />
...
<TextView
     android:id="@+id/tv_main_4"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_marginTop="10dp"
     android:text="@{map[key],default=mapValue}" />

<Button
     android:id="@+id/btn_main_map_update"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@string/string_main_map_update" />

然后我們在MainActivity中給map和key進行賦值,并給按鈕設置點擊事件:

ObservableMap<String, String> map = new ObservableArrayMap<>();
map.put("name", "leavesC");
map.put("age", "24");
binding.setVariable(BR.map, map);
binding.setKey("name");
binding.btnMainMapUpdate.setOnClickListener(v -> map.put("name", "leavesC,hi" + new Random().nextInt(100)));

點擊按鈕發現文本框的內容得到了更新,說明這個map在數據更新時也會通知UI刷新。

4、雙向數據綁定

我們已經做到在數據刷新時更新UI了,但是我們UI變化時能不能讓數據跟著變化呢?很簡單,我們這里先寫一個實體類:

public class MutuallyUpdateBean {

    public final ObservableField<String> content;

    public MutuallyUpdateBean() {
        content = new ObservableField<>();
    }

    public ObservableField<String> getContent() {
        return content;
    }
}

然后在xml中使用這個實體類綁定EditText的輸入內容,并且用一個TextView進行展示:

<variable
    name="mutuallyContent"
    type="com.gegz.gdatabindingdemo2.model.MutuallyUpdateBean" />

<TextView
    android:id="@+id/tv_main_mutually_show"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:text="@{mutuallyContent.content,default=mutuallyContent}" />

<EditText
    android:id="@+id/et_main_mutually_update"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:autofillHints="false"
    android:inputType="text"
    android:text="@={mutuallyContent.content}"
    tools:ignore="LabelFor" />

最后創建一個MutuallyUpdateBean對象傳進去即可:

binding.setVariable(BR.mutuallyContent, new MutuallyUpdateBean());

運行起來,發現我們在EditText中輸入內容時,TextView的內容也發生了相應的變化,說明我們已經完成了雙向綁定,而雙向綁定的寫法則是@={}。

下章預告

在這一章我們了解了DataBinding數據綁定的寫法,以及雙向綁定的實現方式,下一章我們要介紹DataBinding的運算符,這些運算符可以幫助我們很方便的實現一些功能,希望大家能多多支持。

參考文檔:

CSDN:Android DataBinding 運算符、BindingAdapter、 BindingConversion --xiaow

CSDN:Android 安卓DataBinding(九)·運算符 --第三女神程憶難

CSDN:Android DataBinding的基本使用 -- 尹中文

CSDN:Android DataBinding 從入門到進階,看這一篇就夠 -- 程序員一東

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容