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

时间:2017-12-18 07:38:07

标签: android-recyclerview staggeredgridlayoutmanager

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 个答案:

答案 0 :(得分:1)

基于this answer,我想你可以试试:

@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;
    }
}

答案 1 :(得分:0)

我通过设置自定义RecyclerView.ItemDecoration来解决此问题,覆盖方法getItemOffsets并使用StaggeredGridLayoutManager.LayoutParams#getSpanIndex设置不同的背景。

相关问题