androidkotlinandroid-jetpack-composealignment

How to use align(Alignment.BottomCenter) of BOX scope in other compose functions


I am new to Jetpack Compose.

Say I have a root layout BOX, and I want to placing multiple text/button/image views in the BOX. I know I can use align(Alignment.BottomCenter) when I write Text() directly inside the BOX scope.

However, when I try to separate some code to its own compose function like

@Composable
fun ActionButton(label: String,
                      modifier: Modifier = Modifier,
                      action: ()->Unit) {
    Button(onClick = action, modifier = modifier.padding(36.dp).align(Alignment.BottomCenter)) {
        Text(text = label)
    }
}

This will give me error:

Cannot access 'BoxScopeInstance': it is internal in 'androidx.compose.foundation.layout'

Even this ActionButton composable will only be used in my BOX layout.

My question is that is there a way to specify the alignment in compose functions which will only be used in a BOX layout?


Solution

  • This error is causing because the align() function is basically depend on parent like Box, Column or Row. And that's why the compiler has to make sure that you only use this composable function for the specified Scope only. And you have not using any scope for the composable.

    So you could just specify the scope of that composable like in your case just make the function as extension function of BoxScope by changing the declaration by importing the correct scope:

    import androidx.compose.foundation.layout.BoxScope

    ActionButton BoxScope.ActionButtton

    and then your composable should look like this:

    @Composable
    fun BoxScope.ActionButton(label: String,
                     modifier: Modifier = Modifier,
                     action: ()->Unit) {
        Button(onClick = action, modifier = modifier.padding(36.dp).align(Alignment.BottomCenter)) {
            Text(text = label)
        }
    }