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.
Asked
Active
Viewed 2,391 times
2
-
More specifically, see the update on [this answer](https://stackoverflow.com/a/29166336/5288316). – Nicolas Jun 09 '20 at 17:39
-
but where to add method in main activity or in fragment class?? – john Jun 09 '20 at 17:44
-
The answers on the other question tell you that – Ryan M Jun 10 '20 at 01:55
1 Answers
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