如果您在片段之间导航并且想要保存视图状态,请将状态保存在onPause() 或onSaveInstanceState()
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
//your code
}
把这个放到fragment类(onViewCreated())或者ActivityonCreate())
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()
}
})
并使用这个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)
}