I want to create a space between items in the grid. The items should all have equal width/height.
What I've tried:
Create a GridLayoutOffsetDecorator
that applies an offset to all grid items:
class GridLayoutOffsetDecorator(var offset: Int) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State?) {
super.getItemOffsets(outRect, view, parent, state)
outRect.set(offset, offset, offset, offset)
}
}
Having an offset of 8dp
creates a 16dp
space between the items. So we still have to apply 8dp
of padding to the outer edges:
<android.support.v7.widget.RecyclerView
android:id="@+id/productList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:padding="8dp" />
The result is:
Problem: the items are not equal in size:
You notice a slight difference in height when you look at the blue line. This difference appears only after padding the recyclerview. This padding seems to slightly resize some of the items. Do you guys have any experience with this problem? Any idea how this can be solved?
By removing the image from the items, the height difference disappears. This is how the image is set:
<SquareImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
app:imageResource="@{product.image}" />
SquareImageView:
class SquareImageView : ImageView {
constructor(context: Context) : super(context)
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)
constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec)
}
}
So the problem may be caused by the image itself.