Recyclerview show different view types
To create RecyclerView
with multiple view type just implement getItemViewType()
, two different ViewHolder
s and take care of the viewType
parameter in onCreateViewHolder()
and bindViewHolder()
.
Short example:
public class MultipleViewTypesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int VIEW_TYPE_FIRST = 0;
private static final int VIEW_TYPE_SECOND = 1;
class ViewHolderFirst extends RecyclerView.ViewHolder {
...
}
class ViewHolderSecond extends RecyclerView.ViewHolder {
...
}
@Override
int getItemViewType(int position) {
return position % 2;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case VIEW_TYPE_FIRST: return new ViewHolderFirst(...);
case VIEW_TYPE_SECOND: return new ViewHolderSecond(...);
...
}
}
@Override
public void bindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case VIEW_TYPE_FIRST:
ViewHolderFirst viewHolderFirst = (ViewHolderFirst)holder;
...
break;
case VIEW_TYPE_SECOND:
ViewHolderSecond viewHolderSecond = (ViewHolderSecond)holder;
...
break;
...
}
}
}