Created
September 9, 2020 06:44
-
-
Save yandroidUA/4153ba0ddb8ef1548e9fb1d7ae372996 to your computer and use it in GitHub Desktop.
BottomSpaceDecoration for RecyclerView item
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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