Reputation: 133
I had big hopes to use the new databinding support on Android to finally get rid of all the boilerplate associated with RecyclerViews, only to find out that the topic is barely mentioned on the official Android databinding docs.
So even thou I found a couple of blog posts with 'tips' on the subject, I'm still looking for a full example implementation on how to avoid having to create an adapter per recyclerview instance.
Here's some reference code, but it's not complete: https://stfalcon.com/en/blog/post/faster-android-apps-with-databinding#takeaways
Upvotes: 1
Views: 299
Reputation: 4740
There is great solution using delegates - http://hannesdorfmann.com/android/adapter-delegates I use it approach with simple changes for DataBinding.
If you are looking for simple way, look at this library https://github.com/drstranges/DataBinding_For_RecyclerView
Any way, even if you are using common way, magic is in bindable ViewHolder:
public class BindingHolder<VB extends ViewDataBinding> extends RecyclerView.ViewHolder {
private VB mBinding;
public static <VB extends ViewDataBinding> BindingHolder<VB> newInstance(
@LayoutRes int layoutId, LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
VB vb = DataBindingUtil.inflate(inflater, layoutId, parent, attachToParent);
return new BindingHolder<>(vb);
}
public BindingHolder(VB binding) {
super(binding.getRoot());
this.mBinding= binding;
}
public VB getBinding() {
return mBinding;
}
}
in onCreateViewHolder
{
BindingHolder holder = BindingHolder.newInstance(R.layout.item,
LayoutInflater.from(parent.getContext()), parent, false);
//set listeners and action handlers
return holder;
}
in onBindViewHolder
{
ItemBinding binding = holder.getBinding();
Item item = items.get(position);
binding.setItem(item);
binding.executePendingBindings();
}
// or
{
ViewDataBinding binding = holder.getBinding();
Object item = items.get(position);
binding.setVariable(BR.item, item);
binding.executePendingBindings();
}
Upvotes: 1