Image for post
Image for post

Android Data Binding: RecyclerView

Reduce, Reuse, Rebind

George Mount
Jan 10, 2017 · 4 min read
RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType);

void onBindViewHolder(RecyclerView.ViewHolder holder, int position);

Android Data Binding in RecyclerView

public class MyViewHolder extends RecyclerView.ViewHolder {
private final ItemBinding binding;

public MyViewHolder(ItemBinding binding) {
super(binding.getRoot());
this.binding = binding;
}

public void bind(Item item) {
binding.setItem(item);
binding.executePendingBindings();
}
}
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
LayoutInflater layoutInflater =
LayoutInflater.from(parent.getContext());
ItemBinding itemBinding =
ItemBinding.inflate(layoutInflater, parent, false);
return new MyViewHolder(itemBinding);
}

public void onBindViewHolder(MyViewHolder holder, int position) {
Item item = getItemForPosition(position);
holder.bind(item);
}

Reusing the ViewHolder

public class MyViewHolder extends RecyclerView.ViewHolder {
private final ViewDataBinding binding;

public MyViewHolder(ViewDataBinding binding) {
super(binding.getRoot());
this.binding = binding;
}

public void bind(Object obj) {
binding.setVariable(BR.obj, obj);
binding.executePendingBindings();
}
}
<variable name="obj" type="Item"/>
public abstract class MyBaseAdapter
extends RecyclerView.Adapter<MyViewHolder> {
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
LayoutInflater layoutInflater =
LayoutInflater.from(parent.getContext());
ViewDataBinding binding = DataBindingUtil.inflate(
layoutInflater, viewType, parent, false);
return new MyViewHolder(binding);
}

public void onBindViewHolder(MyViewHolder holder,
int position) {
Object obj = getObjForPosition(position);
holder.bind(obj);
}
@Override
public int getItemViewType(int position) {
return getLayoutIdForPosition(position);
}

protected abstract Object getObjForPosition(int position);

protected abstract int getLayoutIdForPosition(int position);
}
public abstract class SingleLayoutAdapter extends MyBaseAdapter {
private final int layoutId;

public SingleLayoutAdapter(int layoutId) {
this.layoutId = layoutId;
}

@Override
protected int getLayoutIdForPosition(int position) {
return layoutId;
}
}

What’s Left?

Android Developers

The official Android Developers publication on Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store