Answer the question
In order to leave comments, you need to log in
How to create two even rows in recycler-view?
We need a recycler view (grid layout) with two even rows of images (the indents on the sides of the recycler view and between the images should be the same). How can I do that?
Here is the layout code on which the recycler-view works
<android.support.v7.widget.CardView xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="@color/colorPrimary"
card_view:cardUseCompatPadding="true"
card_view:cardCornerRadius="8dp"
android:layout_marginBottom="16dp">
<ImageView
android:id="@+id/tile_picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
tools:src="@drawable/kfc" />
</android.support.v7.widget.CardView>
Answer the question
In order to leave comments, you need to log in
Alternatively, you can set the width of the card to "match_parent", and specify the padding through RecyclerView.ItemDecorator.
spacing - расстояние между элементами
margin - отступ между крайними элементами и экраном, по умолчанию равно spacing
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
class GridItemDecorator(
private val spacing: Int,
private val margin: Int = spacing
) : RecyclerView.ItemDecoration() {
private val halfSpacing = spacing / 2
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val columns = (parent.layoutManager as? GridLayoutManager)?.spanCount ?: 1
val rows = parent.adapter?.itemCount?.div(columns) ?: 1
val pos = parent.getChildAdapterPosition(view)
fun setTopSpacing() {
if (pos / columns + 1 == 1) {
outRect.top = margin
} else {
outRect.top = halfSpacing
}
}
fun setBottomSpacing() {
if (pos / columns + 1 == rows) {
outRect.bottom = margin
} else {
outRect.bottom = halfSpacing
}
}
fun setLeftSpacing() {
if (pos % columns == 0) {
outRect.left = margin
} else {
outRect.left = halfSpacing
}
}
fun setRightSpacing() {
if (pos % columns == columns - 1) {
outRect.right = margin
} else {
outRect.right = halfSpacing
}
}
setTopSpacing()
setBottomSpacing()
setLeftSpacing()
setRightSpacing()
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question