Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RecyclerView adapter class for using data binding to replace view inflation.
package foo.bar;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import java.util.List;
/**
* RecyclerView adapter class for using data binding to replace view inflation.
*/
public abstract class DataBindingRecyclerViewAdapter<B extends ViewDataBinding> extends
RecyclerView.Adapter<DataBindingRecyclerViewAdapter.ViewHolder<B>> {
@LayoutRes
public abstract int getLayoutResId(int viewType);
@Override
public ViewHolder<B> onCreateViewHolder(ViewGroup parent, int viewType) {
//noinspection unchecked
return new ViewHolder<>((B) DataBindingUtil.inflate(
LayoutInflater.from(parent.getContext()),
getLayoutResId(viewType),
parent,
false));
}
@Override
public void onBindViewHolder(ViewHolder<B> holder, int position) {
onBindViewHolder(holder.getBinding(), position);
}
public abstract void onBindViewHolder(B binding, int position);
@Override
public void onBindViewHolder(ViewHolder<B> holder, int position, List<Object> payloads) {
onBindViewHolder(holder.getBinding(), position, payloads);
}
public void onBindViewHolder(B binding, int position, List<Object> payloads) {
onBindViewHolder(binding, position);
}
@Override
public void onViewRecycled(ViewHolder<B> holder) {
onViewRecycled(holder.getBinding());
}
public void onViewRecycled(B binding) {
}
@Override
public boolean onFailedToRecycleView(ViewHolder<B> holder) {
return onFailedToRecycleView(holder.getBinding());
}
public boolean onFailedToRecycleView(B binding) {
return false;
}
@Override
public void onViewAttachedToWindow(ViewHolder<B> holder) {
onViewAttachedToWindow(holder.getBinding());
}
public void onViewAttachedToWindow(B binding) {
}
@Override
public void onViewDetachedFromWindow(ViewHolder<B> holder) {
onViewDetachedFromWindow(holder.getBinding());
}
public void onViewDetachedFromWindow(B binding) {
}
static class ViewHolder<B extends ViewDataBinding> extends RecyclerView.ViewHolder {
private final B binding;
private ViewHolder(B binding) {
super(binding.getRoot());
this.binding = binding;
}
public B getBinding() {
return binding;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment