RecyclerView
supports multiple view type. getItemViewType will help you to implement multiple view type like itemview, headerview, footerview.
From documentation :
Return the view type of the item at position for the purposes of view recycling.
The default implementation of this method returns 0, making the
assumption of a single view type for the adapter. Unlike ListView
adapters, types need not be contiguous. Consider using id resources to
uniquely identify item view types.
Then you have to check the viewType in onCreateViewHolder(ViewGroup parent,int viewType) method. Depending on the viewType you will create different ViewHolder
.
Sample Code:
@Override
public int getItemViewType(int position) {
if (isPositionHeader(position)) {
return TYPE_HEADER;
} else if (isPositionFooter(position)) {
return TYPE_FOOTER;
}
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
private boolean isPositionFooter(int position) {
return position > mList.size();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (viewType == TYPE_ITEM) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout, viewGroup, false);
return new ItemViewHolder(view);
} else if (viewType == TYPE_HEADER) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.header_layout, viewGroup, false);
return new HeaderViewHolder(view);
} else if (viewType == TYPE_FOOTER) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.footer_layout,
viewGroup, false);
return new FooterViewHolder(view);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof HeaderViewHolder) {
//set the Value from List to corresponding UI component as shown below.
((HeaderViewHolder) holder).txtName.setText(mList.get(position))
//similarly bind other UI components or perform operations
}else if (holder instanceof ItemViewHolder) {
// Your code here
}else if (holder instanceof FooterViewHolder) {
//your code here
}
}
@Override
public int getItemCount() {
// Add two more counts to accomodate header and footer
return this.mList.size() + 2;
}
Check this tutorial.
Also check this answer too.