How to animate the selection in LazyGrid with Android Compose

I am doing the UI effect like this with Android Compose. enter image description here

I implemented with below code. But it's not a good way and it causes bug when drag the Grid. Please give me some suggestions to implement it with diffrent ways.

fun GridView2() {
    var selectedIndex by remember { mutableStateOf(0) }
    var offsetX by remember {
        mutableStateOf((selectedIndex % 4) * 207f)
    }
    var offsetY by remember {
        mutableStateOf((selectedIndex / 4) * 150f)
    }

    val animatedOffset by animateOffsetAsState(
        targetValue = Offset(offsetX, offsetY), label = "",
    )

    Box(modifier = Modifier.fillMaxSize()) {
        LazyVerticalGrid(
            modifier = Modifier
                .fillMaxSize(),
            columns = GridCells.Adaptive(200.dp),
            contentPadding = PaddingValues(0.dp)
        ) {
            items(count = 20) { index ->
                Box(
                    modifier = Modifier
                        .width(200.dp)
                        .height(150.dp)
                        .clickable {
                            selectedIndex = index
                            offsetX = (selectedIndex % 4) * 207f
                            offsetY = (selectedIndex / 4) * 150f
                        },
                    contentAlignment = Alignment.Center
                ) {
                    Box(
                        modifier = Modifier
                            .width(190.dp)
                            .height(140.dp)
                            .background(Color.Gray)
                    )
                }
            }
        }
        Box(
            modifier = Modifier
                .width(207.dp)
                .height(150.dp)
                .offset(
                    x = Dp(animatedOffset.x),
                    y = Dp(animatedOffset.y)
                ),
            contentAlignment = Alignment.Center
        ) {
            Box(
                modifier = Modifier
                    .width(190.dp)
                    .height(140.dp)
                    .border(2.dp, Color.Green)
            )
        }
    }
}


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation