Skip to content

Commit

Permalink
add HorizontalWheelPicker
Browse files Browse the repository at this point in the history
  • Loading branch information
IamCheng5 committed Nov 10, 2022
1 parent 6824a89 commit bd0a3d9
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
1 change: 1 addition & 0 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
Expand Down Expand Up @@ -67,3 +69,55 @@ fun VerticalWheelPicker(
}
}
}

@Composable
fun HorizontalWheelPicker(
modifier: Modifier = Modifier,
count: Int,
state: LazyListState = rememberLazyListState(),
itemWidth: Dp,
visibleItemCount: Int,
onScrollFinish: (index: Int) -> Unit,
content: @Composable BoxScope.(index: Int) -> Unit
) {
val itemHalfWidthToPx = with(LocalDensity.current) { itemWidth.toPx() / 2 }

val currentOnScrollFinish by rememberUpdatedState(onScrollFinish)

LaunchedEffect(state.isScrollInProgress) {
if (!state.isScrollInProgress && state.firstVisibleItemScrollOffset != 0) {
if (state.firstVisibleItemScrollOffset < itemHalfWidthToPx) {
state.animateScrollToItem(state.firstVisibleItemIndex)
} else if (state.firstVisibleItemScrollOffset > itemHalfWidthToPx) {
state.animateScrollToItem(state.firstVisibleItemIndex + 1)
}
}
}

LaunchedEffect(state) {
snapshotFlow { state.isScrollInProgress }
.filter {
!it && state.firstVisibleItemScrollOffset == 0
}
.drop(1)
.collect {
currentOnScrollFinish(state.firstVisibleItemIndex)
}
}

LazyRow(
modifier = modifier.width(itemWidth * visibleItemCount),
state = state,
contentPadding = PaddingValues(horizontal = itemWidth * (visibleItemCount / 2))
) {
items(count = count, key = { it }) { index ->
Box(
modifier = Modifier
.width(itemWidth),
contentAlignment = Alignment.Center
) {
content(index)
}
}
}
}

0 comments on commit bd0a3d9

Please sign in to comment.