Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RecyclerView Sync Scroll Position
// Adapter and data set
class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { ... }
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder { ... }
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { ... }
override fun getItemCount() = dataSet.size
}
val rooms: List<Room> = rooms
val recyclerViewAdapter = CustomAdapter(rooms)
// Horizontle RecyclerView
val horizontalRecyclerView: RecyclerView = findViewById(R.id.recycler_view)
val horizontalLayoutManager: LinearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
horizontalRecyclerView.layoutManager = horizontalLayoutManager
horizontalRecyclerView.adapter = recyclerViewAdapter
// Vertical RecyclerView
val verticalRecyclerView: RecyclerView = findViewById(R.id.recycler_view)
val verticalLayoutManager: LinearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
verticalRecyclerView.layoutManager = verticalLayoutManager
verticalRecyclerView.adapter = recyclerViewAdapter
// ... When vertical list starts to render
// Transfer scroll position from horizontal list to vertical one
val horizontalScrollPosition = horizontalLayoutManager.findFirstVisibleItemPosition()
verticalRecyclerView.scrollToPosition(horizontalScrollPosition)
// ... When horizontal list starts to render
// Transfer scroll postion from vertical list to horizontal one
val verticalScrollPosition = verticalLayoutManager.findFirstVisibleItemPosition()
horizontalRecyclerView.scrollToPosition(verticalScrollPosition)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment