Home > Mobile >  Jetpack Compose Modifier.fillMaxWidth.align fails to compile
Jetpack Compose Modifier.fillMaxWidth.align fails to compile

Time:05-28

Declaring a Box like this results in a compilation error

           Box(modifier = Modifier
                             .fillMaxWidth()
                             .align(Alignment.Center)) {
                            Text(text = "Hello")
                          }

import for align looks like this

import androidx.compose.foundation.layout.BoxScopeInstance.align

Error

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

Compose Version = 1.1.1

Kotlin Version = 1.6.10

Android Studio Version = Android Studio Electric Eel | 2022.1.1 Canary 2

CodePudding user response:

align is supposed to be called from within the content of the Box

Box(
    modifier = Modifier.fillMaxWidth()
) {
    Text(
        modifier = Modifier.align(Alignment.Center),
        text = "foobar"
    )
}

alternatively use contentAlignment

Box(
    modifier = Modifier.fillMaxWidth(),
    contentAlignment = Alignment.Center
) {
    Text(
        text = "foobar"
    )
}

CodePudding user response:

The modifier.align() method can only be used in the Box, Column, Row layout scope.

For example, something like this.

Column(modifier = Modifier.fillMaxWidth()) {
  Text("Hello")
  Text("World", modifier = Modifier.align(Alignment.CenterHorizontally))
  Row(Modifier.align(Alignment.End)) {
     Icon(....)
  }
}

Using align in Column can only set Alignment whose property is Alignment.Horizontal, such as CenterHorizontally, Start, End.

Using align in Row can only set Alignment whose property is Alignment.Vertical such as CenterVertically Top, Bottom.

Use align in Box to set Alignment other than Alignment.Vertical and Alignment.Horizontal, such as TopStart, TopCenter, TopEnd, Center, BottomStart, BottomCenter, BottomEnd.

  • Related