How to use the new StateRestorationPolicy in Java/Kotlin?

Viewed 4844

Since this topic is fairly new, could someone tell me how to use this feature? I am trying to use it in a fragment.

 override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
...
Handler().postDelayed({
        homePostAdapter!!.stateRestorationPolicy =
            RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
    },500)
...
}

Doesn't seem to work like this. Happy to paste the complete fragment class.

For future reading, these links help:

  1. https://medium.com/androiddevelopers/restore-recyclerview-scroll-position-a8fbdc9a9334
  2. https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.Adapter.StateRestorationPolicy
5 Answers

Maybe this will work for you .

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val binding = FragmentMovieActionBinding.bind(view)
        val pagingAdapter =PagingAdapter(lifecycleScope)
        binding.apply {
            rvListTypesMovies.apply {
                adapter= pagingAdapter
                pagingAdapter.stateRestorationPolicy =  RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
                layoutManager =GridLayoutManager(requireContext(), 2)
                setHasFixedSize(true)

Im using databinding and also Flow.

For the state restoration to work, the View needs to have set android:id in layout.xml. Views without ids are not restored.

It doesn't seem to be the case here, but with DataBinding and without RelativeLayout ids appear to be unnecessary - but they're still needed to save and restore state.

Check if your views have ids in XML:

<androidx.core.widget.NestedScrollView 
               [...]
    android:layout_height="match_parent"
    android:id="@+id/nestedScroll"> <-- my restore didn't work because I didn't have this id set up

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_view"
                          [...]
             />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>

And just set your stateRestorationPolicy as:

homePostAdapter!!.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY

Don't add the delay. You just need to set the stateRestorationPolicy just after you initialize your list adapter.

 listAdapter = ListAdapter()

 // Set scroll restore policy
 listdapter.stateRestorationPolicy =
      RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY

You need to add this in your gradle file

implementation "androidx.recyclerview:recyclerview:1.2.0-alpha04"
Related