Skip to content

Instantly share code, notes, and snippets.

@chenzhang2006
Last active August 1, 2022 20:00
Show Gist options
  • Save chenzhang2006/c59b6c66b59dfb3f3f3571e04d6bb62e to your computer and use it in GitHub Desktop.
Save chenzhang2006/c59b6c66b59dfb3f3f3571e04d6bb62e to your computer and use it in GitHub Desktop.
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