Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the new StateRestorationPolicy in Java/Kotlin?

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
like image 368
DarkFantasy Avatar asked Jun 08 '20 15:06

DarkFantasy


People also ask

How do I configure my kotlin adapter?

Go to app > java > package name > right-click > New > Kotlin class/file and name that file as CustomAdapter and then click on OK. After this add the code provided below. Comments are added inside the code to understand the code in more detail.

What is the use of adapter in Kotlin?

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a android. view.

What is DiffUtil in Kotlin?

DiffUtil is a utility class that calculates the difference between two lists and outputs a list of update operations that converts the first list into the second one. It can be used to calculate updates for a RecyclerView Adapter.


1 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.

like image 118
kirara Avatar answered Sep 28 '22 07:09

kirara