How can a add multiple header or dividers in RecyclerView or listview. randomly as highlighted in the image below:
Multiple heading in RecyclerView on the basic of date - Demo Image
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.
onCreateViewHolder() inflates an XML layout and returns a ViewHolder . onBindViewHolder() sets the various information in the list item View through the ViewHolder . This is the moment when the data from our model gets associated, aka "bound" to our view.
Make a list in your constructor of Items:
private ArrayList<Item> list;
...
public AdapterMain() {
list.add(new HeaderItem());
list.add(new NormalItem());
list.add(new HeaderItem());
list.add(new NormalItem());
}
public Item getItem(int position) {
return list.get(position);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (viewType == Item.TYPE_NORMAL) {
View v = inflater.inflate(R.layout.adapter_normal, viewGroup, false);
return new NormalViewHolder(v);
} else if (viewType == Item.TYPE_HEADER) {
View v = inflater.inflate(R.layout.adapter_header, viewGroup, false);
return new HeaderViewHolder(v);
}
return null;
}
@Override
public int getItemViewType(int position) {
return list.get(position).getItemType();
}
@Override
public int getItemCount() {
return list.size();
}
public abstract class Item {
public static final int TYPE_HEADER = 0;
public static final int TYPE_NORMAL = 1;
public abstract void bindToViewHolder(RecyclerView.ViewHolder holder);
public abstract int getItemType();
}
The actual Header item: (Make also a NormalItem class and a NormalViewHolder class)
public class HeaderItem extends Item {
public HeaderItem() {
super();
}
@Override
public void bindToViewHolder(RecyclerView.ViewHolder viewholder) {
HeaderItem holder = (HeaderItem) viewholder;
holder.title.setText("Header");
}
@Override
public int getItemType() {
return Item.TYPE_HEADER;
}
}
public class HeaderViewHolder extends RecyclerView.ViewHolder {
TextView title;
public HeaderViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.textview);
}
}
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