2

I have a Column with TextViews with indices from -10 to 10.

 Column(
        modifier = modifier
            .verticalScroll(
                state = scrollState,
                enabled = isScrollEnabled,
                reverseScrolling = reverseScrollDirection
            )) {
    for(i in -10..10) {
        TextView("Index $i")
    }
}

Naturally, this Column start with -10 and is incrementing by 1 until 10; so I have to scroll forward all the 21 indices (picture left hand side).

enter image description here

How can I align 0 to the beginning, so that I start the view scrollable either 10 back until -10 or 10 forward until 10 (see attached picture right hand side)?

Ralf Wickum
  • 2,850
  • 9
  • 55
  • 103
  • 1
    Does this answer your question? [Jetpack compose code to scroll down to the position of a specific UI element on clicking a Text](https://stackoverflow.com/questions/67586828/jetpack-compose-code-to-scroll-down-to-the-position-of-a-specific-ui-element-on) – MXC Mar 07 '22 at 21:23

3 Answers3

0

Column doesn't have a concept of item, it has just a bunch of composable functions called inside of it. Because of that, ScrollState only has a method to scroll to position in pixels.

If you know the height of your items, you can calculate the pixel position and pass it to rememberScrollState(). Otherwise, you can use LazyColumn which can scroll to specific item.

Jan Bína
  • 3,447
  • 14
  • 16
0

you can scroll to the last item like this:

val scrollState = rememberScrollState()
val coroutineScope = rememberCoroutineScope()
Button(onClick = {
coroutineScope.launch { 
scrollState.scrollBy((scrollState.maxValue - scrollState.value).toFloat())
}
 }) {
        Text(text = "Scroll To Last Item")
    }
0

Firstly retrieve that specific item's position using a Modifier.onGloballyPositioned, then scroll to that item using LaunchedEffect.

@Composable
fun SmartScrollableColumn() {

    var itemPosition by remember { mutableStateOf(0F) }
    val scrollState = rememberScrollState()

    LaunchedEffect(key1 = Unit) {
        scrollState.animateScrollTo(itemPosition.toInt())
    }

    Column(
        modifier = Modifier.verticalScroll(state = scrollState)
    ) {
        for (i in -10..10) {
            Text(
                text = "Index $i",
                modifier = Modifier
                    .then(
                        // Only store the position of this item (in this case item zero):
                        if (i == 0) Modifier.onGloballyPositioned { layoutCoordinates ->
                            itemPosition = layoutCoordinates.positionInRoot().y
                        } else Modifier
                    )
                    .padding(all = 5.dp)
            )
        }
    }

}
Mostafa Arian Nejad
  • 1,278
  • 1
  • 19
  • 32