Как добавить разделитель между каждой сеткой RecyclerView?
Мне нужно добавить разделитель между каждой сеткой RecyclerView.
RecyclerView recyclerView= (RecyclerView) profileView.findViewById(R.id.profile_recycler_view);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
Adapter Adapter = new Adapter(getActivity());
recyclerView.setAdapter(profileAdapter);
Пожалуйста, помогите мне.
Пример:
2 ответа
Тебе нужно Decoration
за это.
Вот пример:
public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
private int offset;
public ItemOffsetDecoration(int offset) {
this.offset = offset;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = offset;
outRect.right = offset;
outRect.bottom = offset;
if(parent.getChildAdapterPosition(view) == 0) {
outRect.top = offset;
}
}
}
И в твоей деятельности / фрагмент
grid.setLayoutManager(new GridLayoutManager(this, 2));
grid.addItemDecoration(new ItemOffsetDecoration(1));
Я думаю, что Джагадеш Сирам говорил о горизонтальном разделителе между предметами, но RecyclerView.ItemDecoration
добавляет разделитель везде.
Если вы не используете автопрокрутку до какого-либо элемента, вы должны написать так:
public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
private int offset;
public ItemOffsetDecoration(int offset) {
this.offset = offset;
}
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
int bottonIndex;
if (parent.getAdapter().getItemCount() % 2 == 0){
bottonIndex = parent.getAdapter().getItemCount() - 2;
} else {
bottonIndex = parent.getAdapter().getItemCount() - 1;
}
if (parent.getChildAdapterPosition(view) < bottonIndex){
outRect.bottom = offset;
} else {
outRect.bottom = 0;
}
if(parent.getChildAdapterPosition(view) > 1 ) {
outRect.top = offset;
} else {
outRect.top = 0;
}
if( (parent.getChildAdapterPosition(view) % 2 ) == 0) {
outRect.right = offset;
outRect.left = 0;
} else {
outRect.right = 0;
outRect.left = offset;
}
}