Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to show only some elements in a lazyList?

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))

like image 227
QenBau Avatar asked Oct 26 '25 10:10

QenBau


2 Answers

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() }
like image 131
nh7 Avatar answered Oct 28 '25 00:10

nh7


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)
                    )
                }
            }
        }
    }
}
like image 23
commandiron Avatar answered Oct 27 '25 23:10

commandiron