How can I create new Modifiers that depend on some other Modifiers' values? Say, for the sake of an example, I want to make the child components's height to be half of the one that is passed in from the parent plus some constant (thus not being able to use fillMaxHeight(fraction: Float)).
@Composable
fun View() {
MyComposable(modifier = Modifier.size(40.dp))
}
@Composable
fun MyComposable(
modifier: Modifier // Assuming this modifier contains a size
) {
Box(modifier) { // Setting the the size from the passed in modifier
val childHeightModifier = Modifier.height(???) // <-- Wanted to be some specific value depending on parent size
Box(childHeightModifier) {
...
}
}
}
CodePudding user response:
You can use BoxWithConstraints
for this particular usecase, it provides constraints imposed by parent to its children:
@Composable
fun View() {
MyComposable(modifier = Modifier.size(40.dp))
}
@Composable
fun MyComposable(modifier: Modifier) {
BoxWithConstraints(modifier) { // this: BoxWithConstraintsScope
val childHeightModifier = Modifier.height(maxHeight * 0.5f)
Box(childHeightModifier) {
...
}
}
}
As for communication between Modifier
s, there's a ModifierLocal
system in the works, which will allow doing exactly that.
CodePudding user response:
Generally there's no way to do that, you can pass this value as an argument.
But in this particular case you can set your view size depending on parent using:
.fillMaxHeight(fraction = 0.5f)
where fraction is part of the parent view, e.g. equivalent of.height(heightDp * 0.5f)
.padding(left = 10.dp)
(orright
) to descries the size by a static value.
Changing order of fillMaxHeight
and padding
will give you different effect too(.height(heightDp * 0.5f - 10.dp)
vs (heightDp - 10.dp) * 0.5f
), check out more about modifiers order in this answer