'Jetpack Compose LazyVerticalGrid items having a different size
When I'm trying to use LazyVerticalGrid to display a list of images, some grid items have a different size even the images itself have exactly same size 240x178.
I tied to use modifier.fillMaxWidth()
, modifier.matchParentSize()
, modifier.fillMaxHeight()
, modifier.fillMaxWidth()
, modifier.fillParentMaxHeight()
, modifier.fillParentMaxWidth()
, modifier.requiredHeight(imageHeight)
, modifier.requiredWidth(imageWidth)
but nothing had helped me to make images fill all available space without leaving any empty spaces between and some images continue to be not the same size with the others.
Below is my current implementation and I'm using Coil for image loading if its important
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun TreasureGrid(treasures: List<MapTreasure>) {
val configuration = LocalConfiguration.current
val imageWidth = configuration.screenWidthDp.dp / 4
val imageHeight = (imageWidth.times(1.348f))
LazyVerticalGrid(
cells = GridCells.Adaptive(imageWidth)
) {
items(treasures.size) {
TreasureItem(
treasures[it],
Modifier.requiredHeight(imageHeight).requiredWidth(imageWidth)
)
}
}
}
@Composable
fun TreasureItem(mapTreasure: MapTreasure, modifier: Modifier) {
val resId = TMApplication.instance.resources.getIdentifier(
mapTreasure.image,
"drawable",
TMApplication.instance.packageName
)
val matrix = ColorMatrix()
val isOpened = getUser()?.openedTreasures?.contains(mapTreasure.name) == true
if (isOpened.not()) {
matrix.setToSaturation(0F)
}
Box {
AsyncImage(
model = resId,
contentDescription = mapTreasure.description,
modifier = modifier.clickable {
if (isOpened) {
activity?.let { DialogUtils.showTreasureInfoDialog(it, mapTreasure) }
} else {
Toast.makeText(activity, "Treasure not found", Toast.LENGTH_SHORT).show()
}
}.matchParentSize(),
colorFilter = ColorFilter.colorMatrix(matrix)
)
val alpha = if (isOpened) 0f else 1f
AsyncImage(
model = R.drawable.treasure_key,
contentDescription = mapTreasure.description,
modifier = modifier.rotate(90f).scale(0.3f).alpha(alpha)
)
}
}
Any suggestions on how to make every grid item same size and remove the padding around it are highly appreciated
Solution 1:[1]
The problem was not related to the code. I found out that the designer gave me images of the same size but with different paddings on each image, so the problem was in the image resource itself.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mikhail |