我有一个使用StaggeredGridLayoutManager的RecyclerView,例如2列,我想为第一列和第二列设置不同的背景,如何做到这一点,提前感谢。
基于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;
}
}
我通过设置自定义RecyclerView.ItemDecoration
来解决这个问题,覆盖方法getItemOffsets
并使用StaggeredGridLayoutManager.LayoutParams#getSpanIndex
to设置不同的背景。