androidkotlinandroid-jetpack-composealignment

Modifier Alignment.TopEnd cannot resolve


I want to place a button in the top-right corner, but none of the imported libraries give me this option.

Row {
    Button(
        colors = mainButtonColor,
        modifier = Modifier
            .align(Alignment.TopEnd)
            .border(width = 2.dp, color = Color.Yellow)
            .weight(1f)
            .shadow(3.dp),
        onClick = {},
    ) {
        // ...
    }
}

I get the following error message:

Type mismatch.

Required: Alignment.Vertical

Found: Alignment


Solution

  • There are various versions of the align modifier and none of them can be used as-is. That is because they are all defined as members of a specific interface, so to use the modifier your code must be executed in the context of such an interface. Now, the Row that is the parent of your Button provides such a context for its children, a RowScope. The only align modifier you can use is the one declared in that interface:

    fun Modifier.align(alignment: Alignment.Vertical): Modifier
    

    As you can see, for this align modifier the parameter must be of type Alignment.Vertical, so you cannot align horizontally. That makes sense: The Row is a layout composable that distributes its children in a row, hence the name. Therefore the horizontal positioning is already taken care of, an additional alignment is neither necessary nor possible.

    That's the reason why your attempt of Alignment.TopEnd doesn't work: It is of type Alignment and also contains a horizontal component, which is forbidden in a Row.

    You have two options: Either choose one of the vertical alignments, namely Alignment.Top, Alignment.CenterVertically or Alignment.Bottom, or you replace your Row with something that provides a scope that allows an alignment horizontally as well as vertically, like a Box. Then you can use Alignment.TopEnd again.

    Additional note: By setting the horizontalArrangement parameter of the Row you can define how the elements in the row are spaced. If your Button is the last element in the row you can use this parameter to make sure there is no addional space to the right, effectively putting it at the End. In combination with the Button's Alignment.Top that might be good enough. For an animated description of how horizontalArrangement works, see https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Arrangement.