Last active
June 4, 2023 19:40
-
-
Save hamedsj/727aad238e9886bd01d1cc86f1e746fd to your computer and use it in GitHub Desktop.
Simple Custom Linear Layout Manager
This file contains 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 androidx.recyclerview.widget.RecyclerView | |
import androidx.recyclerview.widget.RecyclerView.Recycler | |
import java.lang.Integer.max | |
import java.lang.Integer.min | |
class HamidGridLayoutManager: RecyclerView.LayoutManager() { | |
var offset = 0 | |
override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams { | |
return RecyclerView.LayoutParams( | |
RecyclerView.LayoutParams.WRAP_CONTENT, | |
RecyclerView.LayoutParams.WRAP_CONTENT | |
) | |
} | |
override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State?) { | |
fill(recycler) | |
} | |
private fun fill(recycler: Recycler) { | |
if (itemCount == 0) return | |
detachAndScrapAttachedViews(recycler) | |
for (position in 0 until itemCount) { | |
val view = recycler.getViewForPosition(position) | |
addView(view) | |
val layoutParams = view.layoutParams as RecyclerView.LayoutParams | |
layoutParams.width = width | |
layoutParams.height = width | |
view.layoutParams = layoutParams | |
var left = 0 | |
var right = left + width | |
var top = position * width - offset | |
var bottom = top + width | |
measureChild(view, width, width) | |
layoutDecorated(view, left, top, right, bottom) | |
} | |
val scrapListCopy = recycler.scrapList.toList() | |
scrapListCopy.forEach { | |
recycler.recycleView(it.itemView) | |
} | |
} | |
override fun canScrollVertically(): Boolean { | |
return true | |
} | |
override fun scrollVerticallyBy( | |
dy: Int, | |
recycler: Recycler?, | |
state: RecyclerView.State? | |
): Int { | |
if (itemCount == 0) return 0 | |
val lastOffset = offset | |
val firstItem = requireNotNull(getChildAt(0)) | |
val lastItem = requireNotNull(getChildAt(itemCount - 1)) | |
val startOfFirstItem = getDecoratedTop(firstItem) | |
val endOfLastItem = getDecoratedBottom(lastItem) | |
offset = min(max(startOfFirstItem, offset + dy), offset + endOfLastItem - height) | |
return lastOffset - offset | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment