1

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.

twlkyao
  • 14,302
  • 7
  • 27
  • 44

2 Answers2

1

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;
    }
}
Hai Hack
  • 948
  • 13
  • 24
0

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

twlkyao
  • 14,302
  • 7
  • 27
  • 44