Last active
February 16, 2016 20:42
-
-
Save niusounds/9c57c0ae5ffb7b47ba62 to your computer and use it in GitHub Desktop.
How to simplify RecyclerView.Adapter and RecyclerView.ViewHolder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import org.androidannotations.annotations.EBean; | |
public class MyAdapter extends SimpleListAdapter<String, TextView> { | |
public MyAdapter(Context ctx) { | |
super(ctx); | |
} | |
@Override | |
protected TextView newView(Context ctx) { | |
return new TextView(ctx); | |
} | |
@Override | |
protected void bind(String value, TextView view) { | |
view.setText(value); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.support.v7.widget.RecyclerView; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import java.util.Collections; | |
import java.util.List; | |
public abstract class SimpleListAdapter<T, V extends View> extends RecyclerView.Adapter<SimpleListAdapter.ViewHolder<V>> { | |
private List<T> list = Collections.emptyList(); | |
private Context ctx; | |
public SimpleListAdapter(Context ctx) { | |
super(); | |
this.ctx = ctx; | |
} | |
protected abstract V newView(Context ctx); | |
protected abstract void bind(T value, V view); | |
@Override | |
public ViewHolder<V> onCreateViewHolder(ViewGroup viewGroup, int pos) { | |
return new ViewHolder<V>(newView(ctx)); | |
} | |
@Override | |
public void onBindViewHolder(ViewHolder<V> viewHolder, int pos) { | |
bind(list.get(pos), viewHolder.view); | |
} | |
@Override | |
public int getItemCount() { | |
return list.size(); | |
} | |
public void setList(List<T> list) { | |
this.list = list; | |
} | |
public List<T> getList() { | |
return list; | |
} | |
public static class ViewHolder<V extends View> extends RecyclerView.ViewHolder { | |
V view; | |
public ViewHolder(V v) { | |
super(v); | |
view = v; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thx for your Adapter which was a great inspiration for mine : https://gist.github.com/Plumillon/f85c6be94e2fdaf339b9