I have read a lot of similar articles but still didnt find answer how to know view holder is left or right in RecyclerView
with StaggeredGridLayoutManager
.
Situation:
I have RecyclerView
, StaggeredGrid and want to do padding like
8 dp [left view] 8 dp [right view] 8 dp
So since I cannot do it in XML I have to add some margins -
For left view: left margin 8dp, right margin 4dp
For right view: left margin 4dp, right margin 8dp
Usually views are placed like this:
[0][1]
[2][3]
[4][5]
So simpliest solution was to try determine it by position:
override fun onBindViewHolder(ViewHolder holder, int position) {
...
val params = holder.cardView.layoutParams as FrameLayout.LayoutParams
if (position % 2 == 0) {
params.leftMargin = pxFromDp(context, 8f).toInt()
params.rightMargin = pxFromDp(context, 4f).toInt()
}
if (position % 2 == 1) {
params.rightMargin = pxFromDp(context, 8f).toInt()
params.leftMargin = pxFromDp(context, 4f).toInt()
}
params.bottomMargin = pxFromDp(context, 2f).toInt()
params.topMargin = pxFromDp(context, 6f).toInt()
holder.cardView.layoutParams = params
...
}
And that works, but if view 2 has less height than view 1 they are placed
[0][1]
[3][2]
[5][4]
So it does not work.
How can I know if there are left or right viewholder?