2

the problem is I don't know how to save the state of recycler view which is in the inside fragment. when I go new activity and come back to the previous one the recycler view sarts from the top instead of where I stopped scrolling when is searched the internet they are suggestion to implement saving instance override method but I don't where to put that method means either in the fragment or in the main activity and how to use in onactivitycreated method so that when I come back recycler view does not go to the top.

john
  • 31
  • 5

1 Answers1

1

If you're navigating between fragments and you want to save the view state, you save the state on onPause() or on onSaveInstanceState()

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
  //your code

}

Put this in the fragment class (onViewCreated()) or Activity onCreate())

    var scrolled: Int = 0
        recyclerView!!.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                scrolled += dy //this one ro scroll vertically, if you want to horizontal scroll - change `dy` to `dx`

                val preferences = PreferenceManager.getDefaultSharedPreferences(context)
                preferences.edit()
                    .putInt("position", scrolled)
                    .apply()
            }
        })

And use this onResume()

 override fun onResume() {
    super.onResume()
    val preferences = PreferenceManager.getDefaultSharedPreferences(context)

    val index = preferences.getInt("position", 0)

    Handler().postDelayed({
        recyclerView!!.smoothScrollBy(0, index) //this one ro scroll vertically, if you want to horizontal scroll - `(index,0)`
    }, 50)

}
rhiskey
  • 73
  • 2
  • 6
DarkFantasy
  • 240
  • 3
  • 16