Skip to content

Instantly share code, notes, and snippets.

@oguzhanaslann
Created November 20, 2023 19:55
Show Gist options
  • Select an option

  • Save oguzhanaslann/0a66c3b3277199293687a6697c2dc7bd to your computer and use it in GitHub Desktop.

Select an option

Save oguzhanaslann/0a66c3b3277199293687a6697c2dc7bd to your computer and use it in GitHub Desktop.
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
class CenterScrollLayoutManager(val context: Context, orientation: Int, reverseLayout: Boolean) :
LinearLayoutManager(context, orientation, reverseLayout) {
constructor(context: Context) : this(context, HORIZONTAL, false)
override fun scrollToPosition(position: Int) {
val offset = calculateOffsetForPosition(position)
super.scrollToPositionWithOffset(position, offset)
}
private fun calculateOffsetForPosition(position: Int): Int {
val width = context.resources.displayMetrics.widthPixels
val childWidth = widthOfChildAtPosition(position)
return ((width - (childWidth * 1.5)) / 2).toInt()
}
private fun widthOfChildAtPosition(position: Int): Int {
val child = findViewByPosition(position)
return child?.width ?: 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment