Home > Net >  Jetpack compose Grid with adaptive numbers of columns based on size
Jetpack compose Grid with adaptive numbers of columns based on size

Time:11-28

I am trying to make a grid of text items, witch can vary in size, and I would like for as many items to fix in one row as the size allows.

This is what I got so far For example in this case, Ias you see the first row has space for additional items, while climbing should be Climbing and mountaineering enter image description here

I have been trying to use LazyVerticalGrid, is there any way to automatically calculate span based on item size?

`

LazyVerticalGrid(columns = GridCells.Adaptive(120.dp),
    horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)){
    items(selected.size){i->
        ItemHobbySelected(text = selected[i])
    }
}


@Composable
fun ItemHobbySelected(text: String, onClick: () -> Unit={}){
    Box(modifier = Modifier
        .wrapContentWidth()
        .clip(RoundedCornerShape(8.dp))
        .background(Color.White)) {
        Text(
            modifier = Modifier
                .background(Color.Transparent)
                .padding(16.dp, 8.dp, 16.dp, 8.dp)
                .align(Alignment.Center)
                .clickable(onClick = onClick),
            text = text,maxLines =1,
            color = Color(0xFF3D3D3D)
        )
    }
}

`

CodePudding user response:

For such designs you can use Google Accompanist's FlowLayout. Add the version based on the Compose version you are using.

implementation "com.google.accompanist:accompanist-flowlayout:<version>"

It has two Composables. FlowRow and FlowColumn. You need FlowRow:

FlowRow(
   mainAxisSpacing = 10.dp,
   crossAxisSpacing = 10.dp,
   modifier = Modifier
       .fillMaxWidth()
       .padding(4.dp),
   mainAxisAlignment = MainAxisAlignment.Center
   ) {
      selected.forEach{ item ->
          ItemHobbySelected(text = "//Whatever you want")
}

You can modify the spacings to get your desired layout.

  • Related