DataBinding+ViewModel+LiveData+Room+Rxjava的使用之二DataBinding

DataBinding的數據綁定和簡單使用

其一xml

<TextView
    android:id="@+id/waht"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

activity或者fragment裏賦值

binding.waht.setText("我來設置屬性");

其二xml中的數據綁定

定義一個數據來源bean類

public class Car {
    public String car_top;
    public String car_bottom;

    public String getCar_top() {
        return car_top;
    }

    public void setCar_top(String car_top) {
        this.car_top = car_top;
    }

    public String getCar_bottom() {
        return car_bottom;
    }

    public void setCar_bottom(String car_bottom) {
        this.car_bottom = car_bottom;
    }
}

xml中用法

<layout>
<data>
    <variable
        name="bean"
        type="moc.ludomym.ym.main_xianglong.Car"/>
    <!--type (bean類) name   xml中使用的別名-->
</data>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="moc.ludomym.ym.main_xianglong.MainActivity">

        <TextView
            android:id="@+id/waht"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{bean.car_top}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </LinearLayout>

</layout>

其中數據綁定可以使有@{bean.car_top}直接來使用 這裏面配合着room和livedata特別方便

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章