— Android, Jetpack Compose — 1 min read
In Jetpack Compose, composables accept a Modifier
that alters the appearance or behavior of the composable they are applied to . Modifiers are standard Kotlin objects and can be created by calling one of the Modifier
class functions . These functions can be chained together to compose them .
The order of modifier functions is significant. Since each function makes changes to the Modifier
returned by the previous function, the sequence affects the final result . For example, if you have a Column
with a clickable
and a padding
modifier applied in that order, the whole area including the surrounding padding will be clickable. However, if you reverse the order of these two modifiers, only the area inside the padding will be clickable .
To combine multiple Modifier
objects, you can use the Modifier.then(otherModifier)
function . This function allows you to chain multiple modifiers together while maintaining their order. For example:
1@Composable2fun MyComposable(3 modifier: Modifier = Modifier,4 content: @Composable BoxScope.() -> Unit,5) {6 OtherComposable(7 modifier = Modifier8 .fillMaxWidth()9 .then(modifier),10 content = content,11 )12}
In this example, we have a composable called MyComposable
that accepts a modifier
parameter. Inside this composable, we have another composable called OtherComposable
. We want to apply a default fillMaxWidth
modifier to OtherComposable
, but also allow the caller of MyComposable
to pass in additional modifiers. To do this, we use the Modifier.then(modifier)
function to chain the default fillMaxWidth
modifier with the additional modifier
passed in by the caller .
It's important to note that order matters when chaining modifiers together using Modifier.then
. In this example, since we apply the default fillMaxWidth
modifier before chaining it with the additional modifier
, any width-related modifiers passed in by the caller will override the default fillMaxWidth
modifier.
In summary, Jetpack Compose provides a powerful and flexible way to alter the appearance and behavior of composables using modifiers. The order of these modifiers matters and can be controlled using functions like Modifier.then
. By understanding how these functions work and how to chain them together, you can create complex and customizable UIs with ease.