How to set different background with different column with RecyclerView with StaggeredGridLayoutManager?

349 Views Asked by At

I have a RecyclerView using StaggeredGridLayoutManager, 2 columns for example, I want to set different backgrounds for the first column and second column, how to do this, thanks in advance.

2

There are 2 best solutions below

1
On

Base on this answer, I guess you can try:

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    StaggeredGridLayoutManager.LayoutParams lp =
            (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();

    switch (lp.getSpanIndex()) {
        case 0:
            holder.itemView.setBackgroundColor(Color.GREEN);
            break;
        case 1:
            holder.itemView.setBackgroundColor(Color.RED);
            break;
    }
}
0
On

I solve this by set a custom RecyclerView.ItemDecoration, override the method getItemOffsets and use StaggeredGridLayoutManager.LayoutParams#getSpanIndexto set different backgrounds.