Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding multiple header in Recyclerview or Listview. randomly

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

enter image description here

like image 702
hunkhusain Avatar asked Mar 29 '16 07:03

hunkhusain


People also ask

Which is better ListView or RecyclerView?

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.

What is the difference between onCreateViewHolder and onBindViewHolder?

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.


1 Answers

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);
    }
}
like image 164
Tom Sabel Avatar answered Oct 11 '22 16:10

Tom Sabel