Syncing multiple scrollviews in RecycleView Android Kotlin

Viewed 27

I'm new to android development and have been learning how to build apps in android studio using kotlin.

Part of the project I'm working on uses a RecyclerView. The items being dispalyed by the recyclerView each have a scroll view. I want to set it up so that the scrolling on all the scrollviews are synced.

My solution was to add a onScrollChangeListener to each of the scrollViews and store the position in a LiveData variable. I then add an observer to the LiveData variable and then when ever I detect a change I'll cycle through all the scrollViews in the recyclerView and move them to the correct position.

Currently I can only get it to start wroking after I add an item to the recyclerView, however when I close the app and start it again I'll have to add another item to the recyclerView before it can work again.

Here is my code in my MainActivity:

class MainActivity : AppCompatActivity() {
    private val dataViewModel: DataViewModel by viewModels {
        DataViewModelFactory((application as DataApplication).repository)
    }

    var vsvPosition: MutableLiveData<Int?> = MutableLiveData()

    fun updateScrollPosition(scrollY: Int){
        vsvPosition!!.value = scrollY
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val container = findViewById<RecyclerView>(R.id.calendar_recyclerview)
        val calendarRecyclerView = findViewById<RecyclerView>(R.id.calendar_recyclerview)
        val calendarAdapter = WeekListAdapter()

        calendarRecyclerView.adapter = calendarAdapter
        calendarRecyclerView.layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)

        vsvPosition.observe(this, Observer<Int?> {
            for (i in 0 until container.childCount) {
                val vsv = container.getChildAt(i)
                    .findViewById<ScrollView>(R.id.dayScrollView)
                vsv.smoothScrollTo(0, it!!)
            }
        })

        dataViewModel.allappointments.observe(this, Observer { appointments ->
            appointments?.let {
                notificationAdapter.submitList(it)
                calendarAdapter.submitList(it)

                  for (i in 0 until container.childCount) {
                      val hsv = container.getChildAt(i)
                          .findViewById<ScrollView>(R.id.dayScrollView)
  
                      if (hsv != null){
                          Log.d("kl1","scrollview found")
                          vsv.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
                              vsvPosition!!.value = scrollY
                          }
                      }
                  }
            }
        })
    }
}

Any help will be highly appreciated

0 Answers
Related