第 1 步: 定义两个布局项,一个用于列,另一个用于行
第2步:创建回收器视图适配器,并覆盖以下方法
@Override
public int getItemViewType(int position) {
int viewType;
if ((position + 1) % 10 == 0) {
viewType = VIEW_TYPE_ROW;
} else {
viewType = VIEW_TYPE_COLUMN;
}
return viewType;
}
@Override
public long getItemId(int position) {
/**
* Optimization of notifyDataSetChanged
* Look at documentation for setHasStableIds(true) and getItemId(int position)
*/
return STABLE_ID + position;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case VIEW_TYPE_COLUMN:
// inflate column layout and view holder
break;
case VIEW_TYPE_ROW:
// inflate row layout and view holder
break;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case VIEW_TYPE_COLUMN:
break;
case VIEW_TYPE_ROW:
break;
}
}
初始化适配器时,请执行以下操作
final GridLayoutManager layoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 2);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch (themeAdapter.getItemViewType(position)) {
case ThemeAdapter.VIEW_TYPE_COLUMN:
return 1;
case ThemeAdapter.VIEW_TYPE_ROW:
return layoutManager.getSpanCount();
default:
return layoutManager.getSpanCount();
}
}
});
这里的 themeAdapter 是你的 RecyclerView 适配器。
如果您将
RecyclerView
与 GridLayoutManager
一起使用,则可以使用 setSpanSizeLookup
您需要一个
adapter
和 multiviewtype
mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch(adapter.getItemViewType(position)){
case adapter.TYPE_ROW:
return 2;
case adapter.TYPE_COLUMN:
return 1;
}
}
});