一:Data Binding Library
1.官方介绍:
The Data Binding Library is a support library that allows you to
bind UI components in your layouts to data sourcesin your app
using a declarative format rather thanprogrammatically.
(译:数据绑定库是一个支持库,它允许您将布局中的UI组件绑定到应用程序中的数据
源,而不是通过编程方式。)
简单概括就是“绑定”。
二.使用:
1.在模块build.gradle中添加
android {
...
dataBinding {
enabled = true
}
}
2.xml布局,添加< layout>标签,
< ?xml version="1.0" encoding="utf-8"?>
< layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type="com.holam.names.db.entity.User" />
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.getName()}" />
</android.support.constraint.ConstraintLayout>
</layout>
布局中可能使用到的变量
< variable name="user" type="com.holam.names.db.entity.User" />
在布局中通过“@{}”使用变量属性
android:text="@{user.getName()}"
3.User对象:
public class User {
private String name;
private String passwrod;
public User(String name, String passwrod) {
this.name = name;
this.passwrod = passwrod;
}
public String getName() {
return name;
}
public String getPasswrod() {
return passwrod;
}
}
3.数据绑定
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityTestBinding binding = DataBindingUtil.setContentView(this,
R.layout.activity_test);
User user = new User("text", "111");
binding.setUser(user);
}
在fragment,adapter等可以使用
ListItemBinding binding = DataBindingUtil.inflate(layoutInflater,
R.layout.list_item, viewGroup, false);