Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position selected element at the middle of a Row in Jetpack Compose

How to always center the selected Item inside a Row, here is the sample code:

data class Balance(
    val amount: String,
    val isSelected: Boolean
)

@Composable
fun Test() {
    val scrollState = rememberScrollState()
    val list = remember {
        mutableStateListOf(
            Balance("$342.23", false),
            Balance("€23,342.23", false),
            Balance("£9,934.30", false),
            Balance("BGN 543.43", false),
            Balance("BLR 43.35", true),
            Balance("HUN 492.35", false),
            Balance("JPY 5326", false)
        )
    }
    val paddingHorizontal = 50.dp
    val parentWidth = 400.dp
    Row(
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.Bottom,
        modifier = Modifier
            .padding(horizontal = paddingHorizontal)
            .width(parentWidth)
            .wrapContentHeight()
            .horizontalScroll(scrollState)
    ) {
        list.forEachIndexed { i, item ->
            val (amount, isSelected) = item
            Text(
                text = amount,
                color = if (isSelected) {
                    Color.Red
                } else {
                    Color.Red.copy(
                        alpha = 0.2f
                    )
                },
                fontSize = 15.sp,
                modifier = Modifier
                    .padding(
                        horizontal = 10.dp
                    )
                    .clickable {
                        val selectedIndex = list.indexOfFirst { it.isSelected }
                        list[i] = list[i].copy(isSelected = true)
                        list[selectedIndex] = list[selectedIndex].copy(isSelected = false)
                    }
            )
        }
    }
}

And here is the result:

enter image description here

like image 680
slaviboy Avatar asked Nov 28 '25 14:11

slaviboy


1 Answers

One solution is to add onGloballyPositioned to the Modifier, and calculate the middle position to scroll to:

.onGloballyPositioned { coordinates ->
    if (isSelected) {
        val x = coordinates.positionInParent().x
        val width = coordinates.size.width
        scrollToPosition = x - (parentWidthPx / 2f) + paddingHorizontalPx + (width / 2f)
    }
}

Here is the full Gist source code

And here is the result:

enter image description here

like image 162
slaviboy Avatar answered Nov 30 '25 04:11

slaviboy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!