From 6981433231048eb2769c36a5cc4ee7e13f0f6de4 Mon Sep 17 00:00:00 2001 From: Bnyro Date: Tue, 14 May 2024 21:21:56 +0200 Subject: [PATCH] fix: search results scroll state not preserved when rotating --- .../ui/fragments/SearchResultFragment.kt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/src/main/java/com/github/libretube/ui/fragments/SearchResultFragment.kt b/app/src/main/java/com/github/libretube/ui/fragments/SearchResultFragment.kt index 17dce290a..f07b8fba8 100644 --- a/app/src/main/java/com/github/libretube/ui/fragments/SearchResultFragment.kt +++ b/app/src/main/java/com/github/libretube/ui/fragments/SearchResultFragment.kt @@ -1,6 +1,8 @@ package com.github.libretube.ui.fragments +import android.content.res.Configuration import android.os.Bundle +import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -13,6 +15,7 @@ import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.navArgs import androidx.paging.LoadState import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.RecyclerView import com.github.libretube.R import com.github.libretube.constants.PreferenceKeys import com.github.libretube.databinding.FragmentSearchResultBinding @@ -36,6 +39,8 @@ class SearchResultFragment : DynamicLayoutManagerFragment() { private val args by navArgs() private val viewModel by viewModels() + private var recyclerViewState: Parcelable? = null + override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, @@ -83,6 +88,13 @@ class SearchResultFragment : DynamicLayoutManagerFragment() { val searchResultsAdapter = SearchResultsAdapter(timeStamp ?: 0) binding.searchRecycler.adapter = searchResultsAdapter + binding.searchRecycler.addOnScrollListener(object : RecyclerView.OnScrollListener() { + override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { + super.onScrollStateChanged(recyclerView, newState) + recyclerViewState = binding.searchRecycler.layoutManager?.onSaveInstanceState() + } + }) + viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { searchResultsAdapter.loadStateFlow.collect { @@ -112,6 +124,12 @@ class SearchResultFragment : DynamicLayoutManagerFragment() { } } + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + // manually restore the recyclerview state due to https://github.com/material-components/material-components-android/issues/3473 + binding.searchRecycler.layoutManager?.onRestoreInstanceState(recyclerViewState) + } + override fun onDestroyView() { super.onDestroyView() _binding = null