Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
LinearLayoutManager subclass that "peeks", shows a portion of the adjacent child views.
class PeekingLinearLayoutManager : LinearLayoutManager {
@Suppress("Unused")
@JvmOverloads
constructor(context: Context?, @RecyclerView.Orientation orientation: Int = RecyclerView.VERTICAL, reverseLayout: Boolean = false) : super(context, orientation, reverseLayout)
@Suppress("Unused")
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
override fun generateDefaultLayoutParams() =
scaledLayoutParams(super.generateDefaultLayoutParams())
override fun generateLayoutParams(lp: ViewGroup.LayoutParams?) =
scaledLayoutParams(super.generateLayoutParams(lp))
override fun generateLayoutParams(c: Context?, attrs: AttributeSet?) =
scaledLayoutParams(super.generateLayoutParams(c, attrs))
private fun scaledLayoutParams(layoutParams: RecyclerView.LayoutParams) =
layoutParams.apply {
when(orientation) {
HORIZONTAL -> width = (horizontalSpace * ratio).toInt()
VERTICAL -> height = (verticalSpace * ratio).toInt()
}
}
private val horizontalSpace get() = width - paddingStart - paddingEnd
private val verticalSpace get() = height - paddingTop - paddingBottom
private val ratio = 0.9f
}
@bolot

This comment has been minimized.

Copy link
Owner Author

@bolot bolot commented Oct 8, 2018

@tinsukE

This comment has been minimized.

Copy link

@tinsukE tinsukE commented Aug 27, 2019

You should use height for the verticalSpace calculation. Tnx for the code!

@bolot

This comment has been minimized.

Copy link
Owner Author

@bolot bolot commented Aug 28, 2019

Good catch!

@andrecardoso

This comment has been minimized.

Copy link

@andrecardoso andrecardoso commented Feb 23, 2021

You might want to add the following change to avoid showing an empty space when there is a single item:

 private fun scaledLayoutParams(layoutParams: RecyclerView.LayoutParams): RecyclerView.LayoutParams {
        if (itemCount == 1) {
            return layoutParams
        }

        return layoutParams.apply {
            when (orientation) {
                HORIZONTAL -> width = (horizontalSpace * ratio).toInt()
                VERTICAL -> height = (verticalSpace * ratio).toInt()
            }
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment