2

I want to create a timepicker in jetpack Compose like this:

enter image description here

To show the values ​​I am using a lazyList, but I cannot find an elegant method to show only 3 elements at a time better than: LazyColumn (modifier = Modifier.height(x.dp))

QenBau
  • 157
  • 5
  • 15

2 Answers2

1

You can show the element you want with color alpha with list index;

@Composable
fun ShowOnlySomeElementsInLazyColumn(
    items: List<String>
) {
    val lazyListState = rememberLazyListState()
    val firstVisibleIndex = lazyListState.firstVisibleItemIndex
    val centerIndex = firstVisibleIndex + 2
    LazyColumn(
        state = lazyListState,
        modifier = Modifier
            .fillMaxWidth()
            .height(100.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        items(items.size){index ->
            when(centerIndex){
                index -> {
                    Text(text = items[index])
                }
                index + 1 -> {
                    Text(text = items[index])
                }
                index - 1-> {
                    Text(text = items[index])
                }
                else -> {
                    Text(
                        text = items[index],
                        color = LocalContentColor.current.copy(alpha = 0f)
                    )
                }
            }
        }
    }
}
commandiron
  • 1,019
  • 1
  • 9
  • 25
1

I had the exact same problem and solved it like this:

@Composable
fun LimitedLazyColumn(items : List<String>, limit : Int) {
    val itemHeightPixels = remember { mutableStateOf(0) }
    LazyColumn(
        modifier = Modifier.height(pixelsToDp(pixels = itemHeightPixels.value * limit))
    ) {
        items(items) { item ->
            Text(
                text = item,
                modifier = Modifier.onSizeChanged { size -> itemHeightPixels.value = size.height }
            )
        }
    }
}

@Composable
private fun pixelsToDp(pixels: Int) = with(LocalDensity.current) { pixels.toDp() }
nhcodes
  • 1,206
  • 8
  • 20