I have RecyclerViewone that I use to display 2 column layouts with some elements in the form of sections, using the full width. This is how I set up my own RecyclerView:
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
recyclerView.setItemAnimator(null);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new SpacesItemDecoration(Utils.dpToPx(8)));
Here is my class SpaceItemDecoration:
private class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
int viewType = adapter.getItemViewType(position);
if (viewType == 1) {
if (map.get(position)) {
outRect.right = space / 2;
outRect.left = Utils.dpToPx(12);
outRect.top = space / 2;
outRect.bottom = space / 2;
} else {
outRect.right = Utils.dpToPx(12);
outRect.left = space / 2;
outRect.top = space / 2;
outRect.bottom = space / 2;
}
} else {
outRect.left = 0;
outRect.right = 0;
outRect.top = 0;
outRect.bottom = 0;
}
}
}
Basically, I check if the element is a type header / heading or is it a regular element that should appear in 2 columns. In addition, I need to know whether a regular item will be displayed on the left or right side.
Here is my method for calculating whether an element will be displayed on the left or right side:
private void prepareMapping(int start, int end) {
LogUtil.i(TAG, "prepareMapping called");
int lastHeaderPosition = -1;
FeedItems currentItem;
for (int i=start; i<end-1; i++) {
currentItem = list.get(i);
if (currentItem.getType() == 0) {
lastHeaderPosition = i;
} else if ((currentItem.getType() == 1) && ((i - lastHeaderPosition) % 2 == 0)) {
map.put(i, false);
} else if ((currentItem.getType() == 1) && ((i - lastHeaderPosition) % 2 != 0)) {
map.put(i, true);
}
}
}
, , - , , RecyclerView , , . GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS , , .
, GAP_HANDLING_NONE, RecyclerView - . ?