Android DataBinding 数据双向绑定

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);
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容