How to center elements in Column with vertical scroll?

403 Views Asked by At

I have Column with a verticalScroll(rememberScrollState()). The problem is that under certain conditions I need to center certain elements. But I can't do it, as far as I understand it happens due to the fact that the column has an infinite height.But I need all the content to be located inside Column with a verticalScroll(rememberScrollState()). Can this be achieved? Please help me.

enter image description here

1

There are 1 best solutions below

5
On

Try to add .height(IntrinsicSize.Max) to scrollable Column

[the code is checked in the real app, screenshots below, Android 13]

Scaffold { paddingValues ->
        ScreenBackground(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {

            Column(
                modifier = Modifier
                    .padding(16.dp)
                    .verticalScroll(rememberScrollState())
                    .height(IntrinsicSize.Max)
            ) {

                Header()

                // If you remove Items, 
                // Footer will be centered at the screen 
                // as you could see on the attached screenshots
                Item(text = "Item 1")
                Item(text = "Item 2")
                Item(text = "Item 3")

                Box(
                    modifier = Modifier
                        .fillMaxSize()
                ) {
                    Footer(modifier = Modifier.align(Alignment.Center))
                }
            }

        }
    }
@Composable
fun ScreenBackground(
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit
) {
    val color = MaterialTheme.colorScheme.background

    Surface(
        color = if (color == Color.Unspecified) Color.Transparent else color,
        modifier = modifier.fillMaxSize(),
    ) {
        CompositionLocalProvider(
            LocalAbsoluteTonalElevation provides 0.dp
        ) {
            content()
        }
    }
}

enter image description here

enter image description here

And case when content is scrolled down

enter image description here