Skip to content

Instantly share code, notes, and snippets.

@jaganjan
Created November 25, 2015 10:30
Show Gist options
  • Save jaganjan/6c614e7ec67d7a060093 to your computer and use it in GitHub Desktop.
Save jaganjan/6c614e7ec67d7a060093 to your computer and use it in GitHub Desktop.
Linear layout manager divider item decoration xamarin android
public class SpaceItemDecoration : RecyclerView.ItemDecoration
{
private readonly bool _addSpaceFirstItem;
private readonly bool _addSpaceLastItem;
private readonly int _space;
public SpaceItemDecoration(int space, bool addSpaceFirstItem, bool addSpaceLastItem)
{
_space = space;
_addSpaceFirstItem = addSpaceFirstItem;
_addSpaceLastItem = addSpaceLastItem;
}
public override void GetItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
{
base.GetItemOffsets(outRect, view, parent, state);
if (_space <= 0) return;
if (_addSpaceFirstItem && parent.GetChildLayoutPosition(view) < 1 ||
parent.GetChildLayoutPosition(view) >= 1)
{
if (getOrientation(parent) == LinearLayoutManager.Vertical)
{
outRect.Top = _space;
}
else
{
outRect.Left = _space;
}
}
if (!_addSpaceLastItem || parent.GetChildAdapterPosition(view) != getTotalItemCount(parent) - 1) return;
if (getOrientation(parent) == LinearLayoutManager.Vertical)
{
outRect.Bottom = _space;
}
else
{
outRect.Right = _space;
}
}
private int getOrientation(RecyclerView parent)
{
if (parent.GetLayoutManager() is LinearLayoutManager)
{
return ((LinearLayoutManager)parent.GetLayoutManager()).Orientation;
}
throw new NotSupportedException("SpaceItemDecoration can only be used with a LinearLayoutManager.");
}
private int getTotalItemCount(RecyclerView parent)
{
return parent.GetAdapter().ItemCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment