I use a LazyColumn in Jetpack Compose and draw 2 canvas items (4 if screen is rotated) on each row. When i click on one canvas item, I want the canvas to be disabled (background red). I also draw a text item on each canvas to see the index number. This looks something like this (numRows = 64):
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 8.dp)) {
items(numRows) { rowIndex ->
...
CanvasRow(rowIndex,...)
}
}
In CanvasRow I draw the canvas items, a text with the current index and have click listeners like this:
@Composable
fun CanvasRow(
canvasIndex: Int,
modifier: Modifier = Modifier,
disabled: Boolean)
{
Surface(
modifier = modifier
.fillMaxSize()
.pointerInput(Unit) {
detectTapGestures(
onTap = { mMainViewModel.onClicked(canvasIndex) },
onLongPress = {
mMainViewModel.onLongClicked(canvasIndex)
},
)
}
.background(if (disabled) Color.Red else Color.Black),
color = Color.Transparent
) {
Canvas(modifier = Modifier.fillMaxSize()) {
...
}
drawPoints(
points = points,
color = Color.White,
strokeWidth = 2.0f,
pointMode = PointMode.Polygon
)
drawIntoCanvas { canvas ->
val text = (canvasIndex + 1).toString()
val fontSize = 12.sp
val textColor = Color.White.copy(alpha = 0.75f)
val textX = 20f
val textY = fontSize.toPx() + 10f
canvas.nativeCanvas.drawText(text, textX, textY, textPaint)
}
}
}
}
So, when my ViewModel data changes, the ui is recomposed and the canvas items are drawn and all the text items have the correct index. When I scroll down or up, everything works and looks good. Only thing is, when I click on an canvas item after scrolled down or up, the wrong index is passed to my Viewmodel. I know, that there is a key identifier in LazyColumn, but I don´t know how to use this in this case correctly, because I don´t get the items from my Viewmodel directly, I draw periodically some data on the canvas items when my data in my Viewmodel changes. How can I solve this problem that my Viewmodel gets the incorrect item index when I click on a canvas after scrolling down or up in LazyColumn?
If anyone is interested, I used an alpha version of Compose which caused all the problems! After changing the version to a stable Compose version, everything works as expected. Never thought, that this would be such a problem!