Reputation: 31
I'm building a custom time picker similar to the one in the provided image:Time Picker This time picker should exhibit a specific behavior: when reaching the end of the hour or minute list (e.g., reaching 12 for hours or 59 for minutes), it should wrap around to the beginning (0 or 00) without visually scrolling back to the top.
Current Solution (Working): I've implemented a solution that achieves the desired functionality. However, I'm seeking feedback and suggestions from the community for potential improvements or alternative approaches.
Looking for Feedback: Are there any optimizations I can make to my existing solution? Can you suggest a different implementation that might be more efficient or elegant? Are there any accessibility considerations I should be aware of regarding this custom time picker?
Feel free to share your working solution (code snippet) in the next section for review. If you encountered any specific challenges during implementation, mention them here.
val list = MutableList(12) { it + 1 }
@Composable
fun FlatTimePicker(
modifier: Modifier = Modifier,
listState: LazyListState = rememberLazyListState(),
coroutineScope: CoroutineScope = rememberCoroutineScope()
) {
val items = remember {
mutableStateListOf(
list[0],
list[1],
list[2],
list[3],
list[4],
list[5],
list[6],
list[7],
list[8],
list[9],
list[10],
list[11],
)
}
val index = remember { derivedStateOf { listState.firstVisibleItemIndex } }
LazyColumn(
modifier = Modifier
.height(60.dp)
.width(20.dp), state = listState
) {
items(items) {
Text(
text = it.toString(),
style = MaterialTheme.typography.bodyLarge,
textAlign = TextAlign.Center,
)
}
infiniteScroll(
listState = listState,
items = items,
index = index.value,
loadMoreToEnd = {
items.addAll(list)
Log.v("HoursItems", items.toString())
},
loadMoreToStart = {
items.addAll(0, list)
Log.v("HoursItems", items.toString())
},
removeFirst12Items = {
items.removeRange(0, 12)
},
removeLast12Items = {
items.removeRange(items.lastIndex - 12, items.lastIndex)
},
coroutineScope = coroutineScope,
)
}
}
private inline fun LazyListScope.infiniteScroll(
listState: LazyListState,
items: List<Any>,
index: Int,
crossinline loadMoreToEnd: () -> Unit,
crossinline loadMoreToStart: () -> Unit,
crossinline removeFirst12Items: () -> Unit,
crossinline removeLast12Items: () -> Unit,
coroutineScope: CoroutineScope,
) {
if (index + 3 == items.lastIndex && !listState.isScrollInProgress) {
coroutineScope.launch {
loadMoreToEnd()
}
}
if (listState.firstVisibleItemIndex == 0 && !listState.isScrollInProgress) {
coroutineScope.launch {
loadMoreToStart()
listState.scrollToItem(listState.firstVisibleItemIndex + 12)
}
}
if(items.size==24&&listState.firstVisibleItemIndex>items.lastIndex-(items.size/4)) {
coroutineScope.launch {
removeFirst12Items()
}
}
if(items.size==24&&listState.firstVisibleItemIndex<(items.size/4)) {
coroutineScope.launch {
removeLast12Items()
}
}
}```
Upvotes: 2
Views: 70