diff --git a/app/src/main/java/org/pixeldroid/app/posts/feeds/cachedFeeds/CachedFeedFragment.kt b/app/src/main/java/org/pixeldroid/app/posts/feeds/cachedFeeds/CachedFeedFragment.kt index b8484efe..57ace3a4 100644 --- a/app/src/main/java/org/pixeldroid/app/posts/feeds/cachedFeeds/CachedFeedFragment.kt +++ b/app/src/main/java/org/pixeldroid/app/posts/feeds/cachedFeeds/CachedFeedFragment.kt @@ -9,6 +9,7 @@ import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.paging.* import androidx.paging.LoadState.* +import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.Job import kotlinx.coroutines.flow.* @@ -18,6 +19,7 @@ import org.pixeldroid.app.utils.BaseFragment import org.pixeldroid.app.utils.api.objects.FeedContentDatabase import org.pixeldroid.app.utils.db.AppDatabase import org.pixeldroid.app.utils.db.dao.feedContent.FeedContentDao +import org.pixeldroid.app.utils.limitedLengthSmoothScrollToPosition /** * A fragment representing a list of [FeedContentDatabase] items that are cached by the database. @@ -78,7 +80,7 @@ open class CachedFeedFragment : BaseFragment() { } fun onTabReClicked() { - binding.list.scrollToPosition(0) + binding.list.limitedLengthSmoothScrollToPosition(0) } } diff --git a/app/src/main/java/org/pixeldroid/app/utils/Utils.kt b/app/src/main/java/org/pixeldroid/app/utils/Utils.kt index 4de86c61..8769881b 100644 --- a/app/src/main/java/org/pixeldroid/app/utils/Utils.kt +++ b/app/src/main/java/org/pixeldroid/app/utils/Utils.kt @@ -15,6 +15,8 @@ import androidx.browser.customtabs.CustomTabsIntent import androidx.fragment.app.Fragment import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView import org.pixeldroid.app.R import okhttp3.HttpUrl import kotlin.properties.ReadWriteProperty @@ -79,6 +81,29 @@ fun BaseActivity.openUrl(url: String): Boolean{ } } + +fun RecyclerView.limitedLengthSmoothScrollToPosition(targetItem: Int) { + layoutManager?.apply { + val maxScroll = 3 + when (this) { + is LinearLayoutManager -> { + val topItem = findFirstVisibleItemPosition() + val distance = topItem - targetItem + val anchorItem = when { + distance > maxScroll -> targetItem + maxScroll + distance < -maxScroll -> targetItem - maxScroll + else -> topItem + } + if (anchorItem != topItem) scrollToPosition(anchorItem) + post { + smoothScrollToPosition(targetItem) + } + } + else -> smoothScrollToPosition(targetItem) + } + } +} + /** * @brief Updates the application's theme depending on the given preferences and resources */