Skip to content

Instantly share code, notes, and snippets.

@pankaj89

pankaj89/Usage

Created Dec 23, 2017
Embed
What would you like to do?
SimpleAdapter with DataBinding
public abstract class SimpleAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<T> list;
int layout;
public static <M, B> SimpleAdapter with(int res, ArrayList<M> list, final Binder<M, B> binder) {
return new SimpleAdapter<M>(list, res) {
@Override
public void onBind(int position, M model, ViewDataBinding binding) {
binder.onBind(position, model, (B) binding);
}
};
}
public interface Binder<M, B> {
void onBind(int position, M model, B binding);
}
public SimpleAdapter(ArrayList<T> list, int layout) {
this.list = list;
this.layout = layout;
}
@Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
SimpleViewHolder simpleViewHolder = new SimpleViewHolder(parent, layout);
return simpleViewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
onBind(holder.getAdapterPosition(), list.get(position), ((SimpleAdapter.SimpleViewHolder)holder).binding);
}
public abstract void onBind(int position, T model, ViewDataBinding binding);
@Override
public int getItemCount() {
return list.size();
}
class SimpleViewHolder extends RecyclerView.ViewHolder {
public ViewDataBinding binding;
public SimpleViewHolder(ViewGroup parent, int res) {
super(LayoutInflater.from(parent.getContext()).inflate(res, parent, false));
binding = DataBindingUtil.bind(itemView);
}
}
@BindingAdapter("simpleAdapter")
public static void setAdapter(RecyclerView recyclerView, SimpleAdapter simpleAdapter) {
recyclerView.setAdapter(simpleAdapter);
}
}
RecyclerView recyclerView = new RecyclerView(this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(SimpleAdapter.with(R.layout.items, list, new SimpleAdapter.Binder<String, ItemsBinding>() {
@Override
public void onBind(int position, String model, ItemsBinding binding) {
binding.txtFirstName.setText(model);
}
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment