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.
What I want to achieve is to have the selected item centered like this
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:
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