使用 SpanSizeLookup 设置 GridLayoutManager 中项的范围

我想用节头实现类似网格的布局

我现在要做的是:

mRecyclerView = (RecyclerView) view.findViewById(R.id.grid);
mLayoutManager = new GridLayoutManager(getActivity(), 2);
mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch(mAdapter.getItemViewType(position)){
case MyAdapter.TYPE_HEADER:
return 1;
case MyAdapter.TYPE_ITEM:
return 2;
default:
return -1;
}
}
});


mRecyclerView.setLayoutManager(mLayoutManager);

现在,常规项和标题的跨度大小都是1。我该如何解决这个问题呢?

63015 次浏览

The problem was that header should have span size of 2, and regular item should have span size of 1. So correct implementations is:

mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch(mAdapter.getItemViewType(position)){
case MyAdapter.TYPE_HEADER:
return 2;
case MyAdapter.TYPE_ITEM:
return 1;
default:
return -1;
}
}
});

Header should have a span equal to the span count of the entire list.

mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch(mAdapter.getItemViewType(position)){
case MyAdapter.TYPE_HEADER:
return mLayoutManager.getSpanCount();
case MyAdapter.TYPE_ITEM:
return 1;
default:
return -1;
}
}
});

Answer to my own question: Override the getSpanSizeLookup() from the Activity after setting the adapter.