简体   繁体   中英

Jetpack compose Grid with adaptive numbers of columns based on size

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在此处输入图像描述

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

`

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM