I'm using the recycleview to show a list. I was wondering how do we show different types of views? As in, different ViewHolders int the same adapter
In the simple listview we used getItemViewType(), anything different in the recycleview?
Simple answer: You should use RecyclerView in a situation where you want to show a lot of items, and the number of them is dynamic. ListView should only be used when the number of items is always the same and is limited to the screen size.
A ViewHolder describes an item view and metadata about its place within the RecyclerView. RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive View.
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;
...
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With