DataBinding
DataBinding
DataBinding是谷歌发布的一种数据绑定的框架,能够省去findviewbyid()的使用,大量减少Activity的代码。
启用DataBinding
dataBinding {
enabled = true
}
xml转换
在xml布局中的根布局中,使用Alt + Enter,点击Convert to data binding layout,就可以转换为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="user"
type="com.wumeng.jetpackproject.databinding.User" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".databinding.DataBindingActivity">
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:text="@{user.name}"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tv_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="@{user.password}"
app:layout_constraintStart_toStartOf="@+id/tv_name"
app:layout_constraintTop_toBottomOf="@+id/tv_name" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
- 使用layout作为根布局。
- data标签用于声明使用的数据。
####### 定义数据
class User {
private String name;
private String password;
public User(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
在Activity中使用
public class DataBindingActivity extends AppCompatActivity {
private ActivityDataBindingBinding dataBindingBinding;
private User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataBindingBinding = DataBindingUtil.setContentView(this, R.layout.activity_data_binding);
user = new User("WM","123456");
dataBindingBinding.setUser(user);
}
}
网友评论