Android DataBinding 数据双向绑定

2020-12-07  本文已影响0人  wangxiaojin

1.需要打开databinding

dataBinding {
        enabled true
    }

2.最外层布局要使用layout

3.data,variable标签将对象引入到xml

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <data>

        <variable
            name="mUser"
            type="com.example.databinding.entity.User" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">


        <TextView
            android:id="@+id/tv_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:text="@{mUser.age}"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:layout_editor_absoluteX="167dp"
            tools:layout_editor_absoluteY="48dp" />

        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="100dp"
            android:onClick="onClick"
            android:text="+"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tv_value" />

        <Button
            android:id="@+id/btn_sub"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="100dp"
            android:onClick="onClick"
            android:text="-"
            app:layout_constraintLeft_toRightOf="@+id/btn_add"
            app:layout_constraintTop_toBottomOf="@+id/tv_value" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

4.实体类继承 BaseObservable


public class User extends BaseObservable {
    private String name;
    private String age;
    @Bindable
    public String getName() {
        return name;
    }

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

    }
    @Bindable
    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
  //数据改变时,刷新数据
        notifyPropertyChanged(BR.age);
    }
}

5.使用databinding对象

mViewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mMUser = new User();
        mMUser.setAge("10");
        mMUser.setName("张三");
        mViewDataBinding.setMUser(mMUser);
上一篇下一篇

猜你喜欢

热点阅读