DataBinding是一种支持库,借助该库,可以使用声明性格式(而非程序化地)将布局中的界面组件绑定到应用中的数据源。布局通常是使用调用界面框架方法的代码在 Activity 中定义的。
1、引入支持
build.gradle的android中添加如下代码,然后sync project:
android {
...
dataBinding {
enabled = true
}
}
2、将现有xml布局转化为databinding布局
首先需要配置以上开启databinding功能。然后在布局的中使用快捷键(我的是使用Alt+Enter),该快捷键在第6行之前的任意一处空白处才可调出,很重要!!!
3、如我的"activity_databind.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">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_onclick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='@{user.name+@string/mine + user.age}'
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
4、定义一个UserBean数据源
public class UserBean {
private String name;
public UserBean(String name, String age) {
this.name = name;
this.age = age;
}
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
5、activity_databind.xml布局中添加data数据绑定
<?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="user"
type="com.vick.componenttest.databinding.UserBean" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_onclick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='@{user.name+@string/mine + user.age}'
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
然后布局会自动生成一个xml名称对应的类,如我的是ActivityDatabindBinding类
6、DataBinding将视图与数据源绑定
public class DataBindActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//绑定视图
ActivityDatabindBinding activityDatabindBinding=DataBindingUtil.setContentView(this, R.layout.activity_databind);
UserBean userBean = new UserBean("我我我我","30");
//后续可通过setUser对数据源做修改,视图将同步刷新
activityDatabindBinding.setUser(userBean);
}
}
以上即为DataBinding的一次简单示例,如有帮助,记得点赞~