ItemData类
public class ItemData {
public ItemData() {
}
public ItemData(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
item.xml 布局
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="item" type="net.dou7.learndatabinding.models.ItemData" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{item.name}"/>
</LinearLayout>
</layout>
BindingViewHolder 类
public class BindingViewHolder<T extends ViewDataBinding> extends RecyclerView.ViewHolder {
private T mBinding;
public BindingViewHolder(T binding) {
super(binding.getRoot());
mBinding = binding;
}
public T getBinding() {
return mBinding;
}
}
MyAdapter 类
public class MyAdapter extends RecyclerView.Adapter<BindingViewHolder<ItemBinding>> {
private List<ItemData> list;
public MyAdapter() {
list = new ArrayList<>();
for (int i = 0; i < 10; i++)
list.add(new ItemData(i + ""));
}
@Override
public BindingViewHolder<ItemBinding> onCreateViewHolder(ViewGroup parent, int viewType) {
ItemBinding binding
= DataBindingUtil.inflate(
LayoutInflater.from(parent.getContext()),
item, parent, false);
return new BindingViewHolder(binding);
}
@Override
public void onBindViewHolder(BindingViewHolder<ItemBinding> holder, int position) {
holder.getBinding().setItem(list.get(position));
// 立即设值
holder.getBinding().executePendingBindings();
}
@Override
public int getItemCount() {
return list.size();
}
}
Activity
public class RecyclerViewDemo extends AppCompatActivity {
RecyclerViewDemoBinding mBinding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.recycler_view_demo);
mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
mBinding.recyclerView.setAdapter(new MyAdapter());
}
}