Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack Compose LazyRow - Center selected item

How can I calculate the position of the selected item in a LazyRow and use it for centering the item on the screen? The items will have various sizes depending on their content.

If I go with lazyListState.animateScrollToItem(index) the selected item will be positioned to the left in the LazyRow. Result

What I want to achieve is to have the selected item centered like this Expected

The code I have currently:

@Composable
fun Test() {
    Column {
        TestRow(listOf("Angola", "Bahrain", "Afghanistan", "Denmark", "Egypt", "El Salvador", "Fiji", "Japan", "Kazakhstan", "Kuwait", "Laos", "Mongolia"))
        TestRow(listOf("Angola", "Bahrain", "Afghanistan"))
    }
}

@OptIn(ExperimentalSnapperApi::class)
@Composable
fun TestRow(items: List<String>) {
    val selectedIndex = remember { mutableStateOf(0) }
    val lazyListState = rememberLazyListState()
    val coroutineScope = rememberCoroutineScope()

    LazyRow(
        modifier = Modifier.fillMaxWidth(),
        state = lazyListState,
        horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
        contentPadding = PaddingValues(horizontal = 12.dp),
        flingBehavior = rememberSnapperFlingBehavior(
            lazyListState = lazyListState,
            snapOffsetForItem = SnapOffsets.Start
        )
    ) {
        itemsIndexed(items) { index, item ->
            TestItem(
                content = item,
                isSelected = index == selectedIndex.value,
                onClick = {
                    selectedIndex.value = index
                    coroutineScope.launch {
                        lazyListState.animateScrollToItem(index)
                    }
                }
            )
        }
    }
}

@Composable
fun TestItem(
    content: String,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Button(
        modifier = Modifier.height(40.dp),
        colors = ButtonDefaults.buttonColors(
            backgroundColor = if (isSelected) Color.Green else Color.Yellow,
            contentColor = Color.Black
        ),
        elevation = null,
        shape = RoundedCornerShape(5.dp),
        contentPadding = PaddingValues(0.dp),
        onClick = onClick
    ) {
        Text(
            modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
            text = (content).uppercase(),
        )
    }
}

The code horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally) is to make sure the LazyRow centers all the items, when there is not enough items for scrolling. Example with 3 items: All centered

I have tried various suggestions posted at similar questions, but with no luck in finding a solution. jetpack-compose-lazylist-possible-to-zoom-the-center-item how-to-focus-a-invisible-item-in-lazycolumn-on-jetpackcompose /jetpack-compose-make-the-first-element-in-a-lazyrow-be-aligned-to-the-center-o

like image 625
Markram Avatar asked Dec 14 '25 18:12

Markram


1 Answers

I found a solution that fits my needs, since I don't expect to navigate to a selected item, without being able to see it.

This solution can't center items that is not visible on the screen.

coroutineScope.launch {
  val itemInfo = lazyListState.layoutInfo.visibleItemsInfo.firstOrNull { it.index == index }
  if (itemInfo != null) {
     val center = lazyListState.layoutInfo.viewportEndOffset / 2
     val childCenter = itemInfo.offset + itemInfo.size / 2
     lazyListState.animateScrollBy((childCenter - center).toFloat())
  } else {
     lazyListState.animateScrollToItem(index)
  }
}

Hope t

like image 200
Markram Avatar answered Dec 16 '25 12:12

Markram