Search code examples
kotlinandroid-studioandroid-jetpack-composelazycolumn

How to make scrollable LazyColumn items?


I am trying to create a LazyColumn. I want to show all the list but for the first item it will fit all the page if I scroll it up it will show second item and so on. The code I am working on is below :

@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun someFunction() {
        val list = listOf(
            "A", "B", "C", "D"
        ) + ((0..100).map { it.toString() })
        LazyColumn(modifier = Modifier.fillMaxHeight()) {
            items(items = list, itemContent = { item ->
                Box(modifier = Modifier
                    .border(2.dp, Color.Black)
                    .fillMaxWidth(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = item,
                        textAlign = TextAlign.Center,
                        fontSize = 56.sp)
                }

            })
        }
}

enter image description here

Here I have a list includes A,B,C,D and numbers from 0 to 100. For example I want to show first A if I scroll up then B will come then if I scroll up or down it will show the next or previous item etc. I have been searching to solve this issue I also find something like isScrollUp or down but I couldn't achieve to implement. If you can give me a sample code or link it will be perfect for me.


Solution

  • What you are looking for is VerticalPager which will allow you to do exactly that instead of using a LazyColumn. here is a simple example of how to do it using VerticalPager:

    val list = mutableListOf("a","b","c","d")
        val state = rememberPagerState(pageCount = {list.size})
        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
    
            VerticalPager(state = state) {
                Box(modifier = Modifier
                    .border(2.dp, Color.Black)
                    .fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = list[it],
                        textAlign = TextAlign.Center,
                        fontSize = 56.sp)
                }
            }
    
        }
    

    for more information about VerticalPager and HorizontalPager check out the Pager documentation