Home > Blockchain >  Horizontal Scrolling inside LazyColumn in Jetpack Compose
Horizontal Scrolling inside LazyColumn in Jetpack Compose

Time:01-13

I'm currently trying to recreate a behavior, upon adding a new element to a LazyColumn the items start shifting to the right, in order to represent a Tree and make the elements easier to read.

The mockup in question:

Nested Tasks Mockup


Documentation

Reading through the Behavior GIF

As you can see in the GIF, the width of the column starts increasing after the elements no longer fit in the screen.


The Question

I want to prevent this effect from happening, so is there any way I could maintain the width of the column to the maximum all the time?

CodePudding user response:

The reason that applying a simple fillMaxWidth will not work because you are telling a composable to stretch to max, but that is impossible because the view itself can stretch indefinitely since it can be horizontally scrollable. I'm not sure why do you want to prevent this behavior but perhaps maybe you want your views to have some initial width then apply the padding, while maintaining the same width. what you can do in such case is simply give your composables a specific width, or what you can do is to get the width of the box and apply them to your composables by width (i used a text in this case)

val localDensity = LocalDensity.current
var lazyRowWidthDp by remember { mutableStateOf(0.dp) }
Box(
    Modifier
        .padding(start = 10.dp)
        .onGloballyPositioned { layoutCoordinates ->  // This function will get called once the layout has been positioned
            lazyRowWidthDp =
                with(localDensity) { layoutCoordinates.size.width.toDp() }  // with Density is required to convert to correct Dp
        }
) {
    val scrollState = rememberScrollState()
    LazyColumn(
        modifier = Modifier
            .fillMaxWidth()
            .horizontalScroll(scrollState)
    ) {
        items(25) { i ->
            Text(
                text = "Hello",
                modifier = Modifier
                    .padding(start = (i * 20).dp)
                    .width(lazyRowWidthDp)
                    .border(1.dp, Color.Green)
            )
        }
        items(25) { i ->
            Text(
                text = "World",
                modifier = Modifier
                    .padding(start = (i * 10).dp)
                    .width(lazyRowWidthDp)
                    .border(1.dp, Color.Green)
            )
        }
    }
}

Edit:

you can apply horizontal scroll to the lazy column itself and it will scroll in both directions

enter image description here

  • Related