在最后一项之后的RecyclerView.ItemDecoration分隔符

时间:2017-04-26 14:18:59

标签: android android-recyclerview

如何在RecyclerView列表中的最后一项之后添加分隔符?

1 个答案:

答案 0 :(得分:2)

您可以在RecyclerView适配器内的itemList中添加元素(可能是模型的空实例)。然后覆盖适配器内的getItemViewType

@Override
public int getItemViewType(int position) {
    int viewType;
    Model item = getItem(position);
    if (item.getId == -1) {
        viewType = R.layout.item_divider;
    } else  {
        viewType = R.layout.item_model;
    }
    return viewType;
}

然后使用onCreateViewHolder方法。

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
                                       int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(viewType, parent, false);
    return new MyViewHolder(v, viewType);
}

最后在ViewHolder上根据viewType夸大视图:

MyViewHolder(View itemView, int viewType) {
        super(itemView);
        if (viewType == R.layout.item_model) {
            //inflate model view
        } else if (viewType == R.layout.item_divider) {
           //inflate divider view
        }
    }

绑定数据时也一样:

void bind(Model model) {
        if (model.getId != -1) {
            //bind your model data
        } else {
           //bind if you need divider data.
        }
    }