Skip to content

Instantly share code, notes, and snippets.

@isfaaghyth
Last active June 7, 2017 04:13
Show Gist options
  • Save isfaaghyth/b31409b491fd240ae85c774df07fb5c3 to your computer and use it in GitHub Desktop.
Save isfaaghyth/b31409b491fd240ae85c774df07fb5c3 to your computer and use it in GitHub Desktop.
Generic Class for Recyclerview Adapter
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
public abstract class ListAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
protected int mLayout;
Class<VH> mViewHolderClass;
Class<T> mModelClass;
ArrayList<T> mData;
public ListAdapter(int mLayout, Class<VH> mViewHolderClass, Class<T> mModelClass, ArrayList<T> mData) {
this.mLayout = mLayout;
this.mViewHolderClass = mViewHolderClass;
this.mModelClass = mModelClass;
this.mData = mData;
}
@Override public VH onCreateViewHolder(ViewGroup parent, int viewType) {
ViewGroup view = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(mLayout, parent, false);
try {
Constructor<VH> constructor = mViewHolderClass.getConstructor(View.class);
return constructor.newInstance(view);
} catch (Exception e){
throw new RuntimeException(e);
}
}
@Override public void onBindViewHolder(VH holder, int position) {
T model = getItem(position);
bindView(holder, model, position);
}
@Override public int getItemCount() {
return mData.size();
}
abstract protected void bindView(VH holder, T model, int position);
private T getItem(int position) {
return mData.get(position);
}
}
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new ListAdapter<String, ItemViewHolder>(R.layout.item_view_holder, ItemViewHolder.class, String.class, data) {
@Override protected void bindView(ItemViewHolder holder, String model, final int position) {
holder.bind(model);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
//clicked
}
});
}
};
recyclerView.setAdapter(adapter);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment