Android databinding 双向绑定(Demo)

时间:2021-07-25 12:13:11

ide : android Studio
gradle :com.android.tools.build:gradle:2.1.3
效果图
Android databinding 双向绑定(Demo)

上面是EditText 下面是 TextView,在EditText输入内容,textview 内容跟随

首先实体类,作者亲测以下两种方式

public class People {
public ObservableField life = new ObservableField();
//======================分割线
//以下方式需 extends BaseObservable
// private String life;
// @Bindable
// public String getLife() {
// return life;
// }
//
// public void setLife(String life) {
// if (this.life != life){
// this.life = life;
// notifyChange();
// }
// }
}

MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        People p = new People();
        p.life.set("life is so cool!");
        binding.setPeople(p);
    }
}

布局:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <import type="com.example.jzl.myapplication.People"></import>
        <variable  name="people" type="People"></variable>
    </data>

    <LinearLayout  xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:background="@color/white" android:orientation="vertical" tools:context="com.example.jzl.myapplication.MainActivity">

        <EditText  android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@={people.life}" />

        <TextView  android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{people.life}" />
    </LinearLayout>
</layout>

即可,
无法实现双向绑定,基本上是跟环境有关,
环境要求:Android Studio 2.1 Preview 3之后版本,gradle:2.1.0-alpha3之后版本
gradle 版本查看:https://jcenter.bintray.com/com/android/tools/build/gradle/
demo链接:http://download.csdn.net/detail/clare_ju/9636064
参考 : http://www.jianshu.com/p/c481d1f4e0b6