1. 在module的buil.gradle文件里面开启对databinding的支持.
android {
...
dataBinding {
enabled = true
}
}
2.修改布局文件,将布局xml修改成dataBinding格式
<?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="u"
type="com.example.jetpack.module.User" />
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{u.name}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</layout>
3.创建module.
public class User extends BaseObservable {
public String name;
public String position;
@Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
@Bindable
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
notifyPropertyChanged(BR.position);
}
}
4.使用dataBinding
public class TestActivity extends AppCompatActivity {
private ActivityTestBinding activityTestBinding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityTestBinding = DataBindingUtil.setContentView(this,R.layout.activity_test);
User user = new User();
user.setName("fdsfd");
activityTestBinding.setU(user);
//试试修改user中的name属性 看ui会不会发生变化吧
new Thread(){
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
user.setName(user.getName()+1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}