Skip to content

Instantly share code, notes, and snippets.

@yandroidUA
Created September 9, 2020 06:44
Show Gist options
  • Select an option

  • Save yandroidUA/4153ba0ddb8ef1548e9fb1d7ae372996 to your computer and use it in GitHub Desktop.

Select an option

Save yandroidUA/4153ba0ddb8ef1548e9fb1d7ae372996 to your computer and use it in GitHub Desktop.
BottomSpaceDecoration for RecyclerView item
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
// ViewHolder of current item, index of item, itemsCount
typealias SpacePredictor = (RecyclerView.ViewHolder, Int, Int) -> Boolean
class BottomSpaceToTopItemDecoration(
val predictor: SpacePredictor
) : RecyclerView.ItemDecoration() {
private var spaceToAddForLastItem: Int? = null
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
val adapter = parent.adapter ?: return
val childPosition = parent.getChildLayoutPosition(view)
val viewHolder = parent.getChildViewHolder(view)
val needActions = predictor(viewHolder, childPosition, adapter.itemCount)
if (needActions && spaceToAddForLastItem == null) {
// need to add space to lastView
val lastViewBottom = parent.findViewHolderForAdapterPosition(adapter.itemCount - 1)?.itemView?.bottom ?: -1
spaceToAddForLastItem = if (lastViewBottom == -1) {
0
} else {
parent.height - view.height - (lastViewBottom - view.bottom)
}
}
if (childPosition == adapter.itemCount - 1) {
spaceToAddForLastItem?.let {
outRect.bottom = it
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment