Android Data Binding: RecyclerView
George Mount
2.2K32

Hi George! I enjoyed with your MyBaseAdapter idea. but I used Generic type for more enjoyment and added on click listener too:

(I added code to a gist here with a example: https://gist.github.com/DHosseiny/ee51978611c431e0afab7cf531deca08)

(T is data model)

public abstract class BaseAdapter<T>
extends RecyclerView.Adapter<BaseAdapter<T>.MyViewHolder> {

BaseAdapter(OnItemClickListener<T> itemClickListener) {
this.itemClickListener = itemClickListener;
}

public interface OnItemClickListener<T> {
void onItemClick(T item);
}
private final OnItemClickListener<T> itemClickListener;

public BaseAdapter<T>.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
LayoutInflater layoutInflater =
LayoutInflater.from(parent.getContext());
ViewDataBinding binding = DataBindingUtil.inflate(
layoutInflater, viewType, parent, false);
return new BaseAdapter<T>.MyViewHolder(binding);
}

@Override
public void onBindViewHolder(BaseAdapter<T>.MyViewHolder holder,
int position) {
final T item = getItemForPosition(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(item);
}
});
holder.bind(item);
}

@Override
public int getItemViewType(int position) {
return getLayoutIdForPosition(position);
}

protected abstract T getItemForPosition(int position);

protected abstract int getLayoutIdForPosition(int position);

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

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

public void bind(T item) {
binding.setVariable(BR.obj, item);
binding.executePendingBindings();
}
}
}