For #21562 - Snap to next item when scrolling

This works by replacing the fling animation with snapping to the next item in
the scroll direction.
upstream-sync
Mugurell 3 years ago committed by mergify[bot]
parent 2bde49f911
commit ea6d5e3d38

@ -0,0 +1,47 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.fenix.compose
import androidx.compose.foundation.gestures.FlingBehavior
import androidx.compose.foundation.gestures.ScrollScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
/**
* [FlingBehavior] for a [LazyRow] that will automatically scroll the list in the fling direction
* to fully show the next item.
*/
@Composable
fun EagerFlingBehavior(
lazyRowState: LazyListState
): FlingBehavior {
val scope = rememberCoroutineScope()
return LazyListEagerFlingBehavior(lazyRowState, scope)
}
private class LazyListEagerFlingBehavior(
private val lazyRowState: LazyListState,
private val scope: CoroutineScope
) : FlingBehavior {
override suspend fun ScrollScope.performFling(initialVelocity: Float): Float {
val firstItemIndex = lazyRowState.firstVisibleItemIndex
val itemIndexToScrollTo = when (initialVelocity <= 0) {
true -> firstItemIndex
false -> firstItemIndex + 1
}
scope.launch {
lazyRowState.animateScrollToItem(itemIndexToScrollTo)
}
return 0f // we've consumed the entire fling
}
}

@ -18,6 +18,7 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
@ -37,6 +38,7 @@ import mozilla.components.service.pocket.PocketRecommendedStory
import mozilla.components.ui.colors.PhotonColors
import org.mozilla.fenix.R
import org.mozilla.fenix.compose.ClickableSubstringLink
import org.mozilla.fenix.compose.EagerFlingBehavior
import org.mozilla.fenix.compose.FakeClient
import org.mozilla.fenix.compose.ListItemTabLarge
import org.mozilla.fenix.compose.ListItemTabLargePlaceholder
@ -96,8 +98,10 @@ fun PocketStories(
) {
// Show stories in a 3 by 3 grid
val gridLength = 3
val listState = rememberLazyListState()
val flingBehavior = EagerFlingBehavior(lazyRowState = listState)
LazyRow {
LazyRow(state = listState, flingBehavior = flingBehavior) {
itemsIndexed(stories.chunked(gridLength)) { rowIndex, columnItems ->
Column(Modifier.padding(end = if (rowIndex < gridLength - 1) 8.dp else 0.dp)) {
for (index in 0 until gridLength) {

Loading…
Cancel
Save