Home > OS >  Jetpack compose LazyGridView not scroll on Column
Jetpack compose LazyGridView not scroll on Column

Time:11-17

When trying to put a LazyVerticalGrid inside a scrollable Column I get the following error:

java.lang.IllegalStateException: Nesting scrollable in the same direction layouts like LazyColumn and Column(Modifier.verticalScroll()) is not allowed. If you want to add a header before the list of items please take a look on LazyColumn component which has a DSL api which allows to first add a header via item() function and then the list of items via items().

I am not making a traditional list, I just have alot of elements that are too big to fit on the screen. Therefore I want the column to scroll so I can see all the elements. Here is my code:

CodePudding user response:

you need to use an item with a span attribute. Assume that your grid view has three items in every row, you can put your item wherever you want with the scrollable screen.

LazyVerticalGrid(cells = GridCells.Fixed(4)) {
    item(span = { GridItemSpan(4) }) { Header() }
    item(span = { GridItemSpan(4) }) { AnotherView() }
    items(gridItems) { GridItemView(it) }
}

CodePudding user response:

If you want to keep some UI elements sticky at the top or bottom, you can play with the Modifier. weight(), for example:

 @Composable
fun SomeScreenContent() {
    val gridItems = List(30){ it.toString() }
    Column(modifier = Modifier.fillMaxSize()) {
        SomeTopContent(modifier = Modifier.weight(0.2f))
        LazyVerticalGrid(
            modifier = Modifier.weight(0.6f),
            columns = GridCells.Fixed(4),
            contentPadding = PaddingValues(8.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(gridItems) { item ->
                GridItem(item)
            }
        }
        SomeBottomContent(modifier = Modifier.weight(0.2f))
    }
}


@Composable
fun SomeTopContent(modifier:Modifier = Modifier) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .background(Color(0xff5077FC)),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center
    ) {
        Text(text = "Top")
    }
}

@Composable
fun SomeBottomContent(modifier:Modifier = Modifier) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .background(Color(0xff4EE180)),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center
    ) {
        Text(text = "Bottom")
    }
}

@Composable
fun GridItem(item: String) {
    Card(modifier = Modifier.size(100.dp)) {
        Text(text = item)
    }
}

Or just use the Scaffold composable function...

  • Related