问题
I had a problem in saving RecyclerView state and it solved by saving layout manager state and using it after resume fragment.(thanks to @HarisDautović)
class TestFragment : Fragment() {
private val testListAdapter: TestListAdapter by lazy {
TestListAdapter()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_test, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
postListView.apply {
layoutManager = StaggeredGridLayoutManager(
2, StaggeredGridLayoutManager.VERTICAL
).apply {
gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS
}
setHasFixedSize(true)
adapter = testListAdapter
}
}
private var layoutManagerState: Parcelable? = null
override fun onPause() {
saveLayoutManagerState()
super.onPause()
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
restoreLayoutManagerState()
}
private fun restoreLayoutManagerState () {
layoutManagerState?.let { postListView.layoutManager?.onRestoreInstanceState(it) }
}
private fun saveLayoutManagerState () {
layoutManagerState = postListView.layoutManager?.onSaveInstanceState()
}
}
but if using paging 3 library it does not work. just importing this library causes problem even not using it in app.
please see this question and accepted answer's comments for more details: RecyclerView with StaggeredGridLayoutManager in ViewPager, arranges items automatically when going back to fragment
回答1:
UPDATE:
my problem solved by using:
testListAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT
and custom restoration logic
OLD ANSWER: problem is from Recyclervew. the paging library using a newer alpha version of recyclerView that have this problem. by importing paging, whole project using this version of recyclerview. forcing to use stable version of RecyclerView solve the problem.
in build.gradle:
android {
...
configurations.all {
resolutionStrategy.eachDependency { details ->
if (details.requested.group == 'androidx.recyclerview') {
details.useVersion "1.1.0"
}
}
}
}
来源:https://stackoverflow.com/questions/65600730/onrestoreinstancestate-not-working-for-recyclerview-layout-manager-if-using-pagi