1、利用 ItemViewType 區分普通項和頭部尾部ide
2、將頭部和尾部的項設置爲佔據整行,而不是像普通項同樣只佔據一個格子佈局
給 RecyclerView 設置 GridLayoutManager 佈局管理器this
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
在適配器中,利用 position 來斷定每一項的類型:頭部,普通項,底部spa
@Override public int getItemViewType(int position) { int dataItemCount = getContentItemCount(); if (mHeaderCount != 0 && position < mHeaderCount) {//頭部View return ITEM_TYPE.ITEM_TYPE_HEADER.ordinal(); } else if (mBottomCount != 0 && position >= (mHeaderCount + dataItemCount)) {//底部View return ITEM_TYPE.ITEM_TYPE_BOTTOM.ordinal(); } else { return ITEM_TYPE.ITEM_TYPE_CONTENT.ordinal(); } }
而後對應不一樣類型建立不一樣佈局code
@Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == ITEM_TYPE.ITEM_TYPE_HEADER.ordinal()) { return onCreateHeaderView(parent); } else if (viewType == ITEM_TYPE.ITEM_TYPE_CONTENT.ordinal()) { return onCreateContentView(parent, viewType); } else if (viewType == ITEM_TYPE.ITEM_TYPE_BOTTOM.ordinal()) { return onCreateBottomView(parent); } return null; }
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { if (adapter.isHeaderView(position) || adapter.isBottomView(position)) { return gridLayoutManager.getSpanCount(); }else{ return 1; } } });
adapter.isHeaderView(position) 和 adapter.isBottomView(position) 的判斷跟 getItemViewType 差很少blog
此時就實現了頭和底部佔據一行,再也不接在普通item後面了get