如何在RecyclerView中一致地向项目视图添加交替背景

rob*_*cab 10 android android-recyclerview

到目前为止,我使用适配器onBindViewHolder根据项目的适配器位置设置交替背景.

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.itemView.setBackgroundResource(position % 2 == 0 ?
            R.color.list_item_background_alternating : R.color.list_item_background);
    ...
}
Run Code Online (Sandbox Code Playgroud)

然而,当做的不仅仅是显示列表时,这会变得更加复杂.例如:当我删除的项目,并调用notifyItemRemoved(index);RecyclerView做一个漂亮的动画和项目视图中消失了.但是,取代已删除的视图不会再次受到约束(出于明显和充分的理由),因此保留了它的旧背景.这导致布局不一致,看起来很难看.当我打电话notifyDataSetChanged();的背景都是正确的,但我失去了动画.

当我使用SortedList(带有a SortedListAdapterCallback)时,我遇到了类似的问题.由于排序似乎发生在视图绑定后,背景是混乱的.

实施此类行为的正确/一致方式是什么?

rob*_*cab 13

好吧,当我在写我的问题时,我想尝试一些我认为不起作用的东西 - 然而,它确实如此.

我创建了一个ItemDecoration并使用它getItemOffset();来设置视图的背景:

public class BackgroundItemDecoration extends RecyclerView.ItemDecoration {

    private final int mOddBackground;
    private final int mEvenBackground;

    public BackgroundItemDecoration(@DrawableRes int oddBackground, @DrawableRes int evenBackground) {
        mOddBackground = oddBackground;
        mEvenBackground = evenBackground;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int position = parent.getChildAdapterPosition(view);
        view.setBackgroundResource(position % 2 == 0 ? mEvenBackground : mOddBackground);
    }
}
Run Code Online (Sandbox Code Playgroud)

我感到有点内疚,我正在兜售getItemOffsets().

有没有人有更清洁/更好的解决方案?

  • 你什么意思?我没有再发帖.我刚回答了自己的问题.这甚至不鼓励吗?在撰写问题时,您可以选择提供答案.请说明为什么这很糟糕. (2认同)